创建继承于UIButton的名为CustomButton的类:
如图1-1所示,UIButton中有两个方法,titleRect用于设置button - titleLable的frame,imageRect用于设置button - imageView的frame
图1-1具体方法内容如下:
创建常量:
custom_button_titleLabel_height // titlelabel的高度
let custom_button_titleLabel_height:CGFloat = 10.0
/**
* 设置文字的frame
**/
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let titleX : CGFloat = 0
let titleY = contentRect.size.height - custom_button_titleLabel_height - 3
let titleW = contentRect.size.width
let titleH = custom_button_titleLabel_height
return CGRect(x: titleX, y: titleY, width: titleW, height: titleH);
}
/**
* 设置图标的frame
**/
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let imageX : CGFloat = 0
let imageY : CGFloat = 0
let imageW = contentRect.size.width
let imageH = contentRect.size.height - custom_button_titleLabel_height - 3
return CGRect(x: imageX, y: imageY, width: imageW, height: imageH);
}
完成上述操作后,我们使用代码创建一个button查看当前效果(如图1-2所示):
图1-2let test = CustomButton(frame: CGRect(x: 10, y: 100, width: 100, height: 49))
test.backgroundColor = UIColor.red
test.setImage(UIImage(named: "tabBar-home-nor"), for: .normal)
test.setTitle("test", for: .normal)
self.view.addSubview(test)
接下来需要设置图片以及文字居中显示,同时需要设置文字的颜色、字体等设置,那么需要重写init方法:
custom_button_titleLabel_font // titleLabel的字体
custom_button_title_color_normal // titleLabel的颜色
custom_button_title_color_highlighted // titleLabel的高亮颜色
let custom_button_titleLabel_height:CGFloat = 10.0
let custom_button_title_color_normal = UIColor(colorLiteralRed: 94/255.0, green: 94/255.0, blue: 94/255.0, alpha: 1)
let custom_button_title_color_highlighted = UIColor(colorLiteralRed: 27/255.0, green: 163/255.0, blue: 242/255.0, alpha: 1)
/**
* 重写init方法
**/
override init(frame: CGRect) {
super.init(frame: frame)
self.setupButtonSubViews()
}
/**
* 实现init?(coder aDecoder: NSCoder),required表示必须要实现的方法
**/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupButtonSubViews()
}
/**
* 在setupButtonSubViews方法中,对图片、文字进行相关设置
**/
func setupButtonSubViews() {
// 内部图片居中
self.imageView?.contentMode = .center
// 文字居中
self.titleLabel?.textAlignment = .center
// 文字颜色-普通
self.setTitleColor(custom_button_title_color_normal, for: .normal)
// 文字颜色-高亮
self.setTitleColor(custom_button_title_color_highlighted, for: .highlighted)
// 字体
self.titleLabel?.font = custom_button_titleLabel_font
}
完成后,重新运行代码,查看效果(图1-3)
图1-3
网友评论