最近在学习swift的过程中,看到了一些自定义UIButton的例子,再此想和大家分享一下,废话不多说,先看下效果图:
1 自定义Button的titleLabel和imageView的frame属性
class LeftImageRightTextButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.font = UIFont.systemFontOfSize(15)
imageView?.contentMode = UIViewContentMode.Center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView?.frame = CGRectMake(0, (height - (imageView?.size.height)!) * 0.5, (imageView?.size.width)!, (imageView?.size.height)!)
titleLabel?.frame = CGRectMake((imageView?.size.width)! + 10, 0, width - (imageView?.size.width)! - 10, height)
}
}
2 对UIView进行扩展
extension UIView {
/// X值
var x: CGFloat {
return self.frame.origin.x
}
/// Y值
var y: CGFloat {
return self.frame.origin.y
}
/// 宽度
var width: CGFloat {
return self.frame.size.width
}
///高度
var height: CGFloat {
return self.frame.size.height
}
var size: CGSize {
return self.frame.size
}
var point: CGPoint {
return self.frame.origin
}
}
3 调用方法
class ViewController: UIViewController {
var manButton = LeftImageRightTextButton()
private var womenButton: LeftImageRightTextButton?
override func viewDidLoad() {
super.viewDidLoad()
// 注意:这里一定要初始化,否则会报错
womenButton = LeftImageRightTextButton()
buildGenderButton(manButton, frame: CGRectMake(50, 50, 100, 50), title: "先生")
buildGenderButton(womenButton!, frame: CGRectMake(150, 50, 100, 50), title: "女士")
}
private func buildGenderButton(button: LeftImageRightTextButton, frame: CGRect, title: String) {
button.setImage(UIImage(named: "v2_noselected"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "v2_selected"), forState: UIControlState.Selected)
button.addTarget(self, action: "genderButtonClick:", forControlEvents: .TouchUpInside)
button.setTitle(title, forState: UIControlState.Normal)
button.frame = frame
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
view.addSubview(button)
}
func genderButtonClick(sender: UIButton) {
print("点击")
sender.selected = !sender.selected
}
}