UIButton 是开发中高频使用的控件,一个好的封装能大大提高代码的整洁度
1. Target封装
......
2. 协议封装
- 创建点击协议
@objc protocol BookHeaderViewDelegate: NSObjectProtocol {
optional func headerViewDidClick(index: Int)
}
- 封装Button
private func buildButtonWithCustom(title: String, frame: CGRect, action: Selector!, tag: NSInteger) {
let button = UIButton(type: .Custom)
button.layer.cornerRadius = 3
button.layer.masksToBounds = true
button.setTitle(title, forState: .Normal)
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.tag = tag
button.addTarget(self, action: action, forControlEvents: .TouchUpInside)
button.frame = frame
button.backgroundColor = UIColor.colorWithCustom(246, g: 36, b: 8)
addSubview(button)
}
- 添加点击方法
private func click(sender: UIButton) {
delegate?.headerViewDidClick!(sender.tag)
}
- 创建按钮
buildButtonWithCustom("菜 谱", frame: CGRectMake(10, 10, (kScreenWith - 30) / 2.0, (kScreenWith - 30) * 0.618 / 2.0), action: #selector(BookHeaderView.click),tag: 1)
3. 闭包封装
......