在UI搭建中经常会碰到一种上图下文的按钮,以下是我分享的一种我常用的自定义按钮图片和文字位置的方法
重写UIButton的layoutSubviews方法实现
override func layoutSubviews() {
super.layoutSubviews()
// 设置imageView
imageView?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
// 设置title
titleLabel?.frame = CGRect(x: 0, y: self.frame.width, width: self.frame.width, height: self.frame.height - self.frame.width)
}
让图片和文字居中显示
private func setupUI(){
// 设置imageView
imageView?.contentMode = .Center
// 设置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: - 设置视图
private func setupUI(){
// 设置imageView
imageView?.contentMode = .Center
// 设置tilte
titleLabel?.textAlignment = .Center
titleLabel?.font = UIFont.systemFontOfSize(15)
setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
}
// 对其子控件重新布局
override func layoutSubviews() {
super.layoutSubviews()
// 设置imageView
imageView?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
// 设置title
titleLabel?.frame = CGRect(x: 0, y: self.frame.width, width: self.frame.width, height: self.frame.height - self.frame.width)
}
}
然后在外面调用该自定义BUTTON就行.
唯一要注意的一点是如果没有关闭高亮效果,按钮在进行点击时会多次进入layoutSubviews方法.在进行GCAffineTransformMakeScale进行放大时,imageView和titleLabel的frame会发生变化而且无法通过CGAffineIdentify还原回去.至于理由我还没搞懂(一脸懵逼)