iOS-swift-自定制ReuseSectionHeaderFooterView

SectionCell类

这里最好用约束而不是指定frame, 推荐用SnapKit
class SectionCell: UITableViewHeaderFooterView {
    private let label = UILabel()
    private let button = UIButton(type: .System)
    var index = 0{
        didSet{
            button.tag = index
            label.text = "hello \(index)"
            button.setTitle("world \(index)", forState: .Normal)
        }
    }
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        contentView.backgroundColor = UIColor.cyanColor()
        addSubview(label)
        addSubview(button)
        
        label.frame = CGRectMake(0, 0, 100, 20)
        button.addTarget(self, action: #selector(SectionCell.buttonClicked(_:)), forControlEvents: .TouchUpInside)
        button.frame = CGRectMake(200, 0, 60, 20)
    }
    
    func buttonClicked(sender: UIButton){
        debugPrint("buttonClicked: ",sender.tag)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

viewDidLoad中 注册HeaderFooter类

override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(SectionCell.classForCoder(), forHeaderFooterViewReuseIdentifier: "Section")
    }

TableView Delegate 实现HeaderFooter复用

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header =   tableView.dequeueReusableHeaderFooterViewWithIdentifier("Section") as! SectionCell
        header.index = section
        return header
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容