在UI搭建中經(jīng)常會(huì)碰到一種上圖下文的按鈕,以下是我分享的一種我常用的自定義按鈕圖片和文字位置的方法
重寫(xiě)UIButton的layoutSubviews方法實(shí)現(xiàn)
override func layoutSubviews() {
super.layoutSubviews()
// 設(shè)置imageView
imageView?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
// 設(shè)置title
titleLabel?.frame = CGRect(x: 0, y: self.frame.width, width: self.frame.width, height: self.frame.height - self.frame.width)
}
讓圖片和文字居中顯示
private func setupUI(){
// 設(shè)置imageView
imageView?.contentMode = .Center
// 設(shè)置tilte
titleLabel?.textAlignment = .Center
titleLabel?.font = UIFont.systemFontOfSize(15)
setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
}
完整代碼
class BGButton: UIButton {
// 屏蔽按鈕高亮效果
override var highlighted: Bool{
get{
return false
}
set{
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 設(shè)置視圖
private func setupUI(){
// 設(shè)置imageView
imageView?.contentMode = .Center
// 設(shè)置tilte
titleLabel?.textAlignment = .Center
titleLabel?.font = UIFont.systemFontOfSize(15)
setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
}
// 對(duì)其子控件重新布局
override func layoutSubviews() {
super.layoutSubviews()
// 設(shè)置imageView
imageView?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
// 設(shè)置title
titleLabel?.frame = CGRect(x: 0, y: self.frame.width, width: self.frame.width, height: self.frame.height - self.frame.width)
}
}
然后在外面調(diào)用該自定義BUTTON就行.
唯一要注意的一點(diǎn)是如果沒(méi)有關(guān)閉高亮效果,按鈕在進(jìn)行點(diǎn)擊時(shí)會(huì)多次進(jìn)入layoutSubviews方法.在進(jìn)行GCAffineTransformMakeScale進(jìn)行放大時(shí),imageView和titleLabel的frame會(huì)發(fā)生變化而且無(wú)法通過(guò)CGAffineIdentify還原回去.至于理由我還沒(méi)搞懂(一臉懵逼)