我想为用户提供一个自定义视图组件库的标头视图的选项。
所以我想遵循UITableViewDataSource
协议并尝试实现这样的事情。
//customview.swift
protocol CustomViewDatasource: class {
func heightForHeader(in view: CustomView) -> CGFloat
func headerView(in view: CustomView) -> UIView
}
class CustomView: UIView {
weak var dataSource: CustomViewDatasource?
/// How can I draw the custom header view passing by dataSource?
}
//viewcontroller.swift
extension ViewController: CustomViewDatasource {
...
func headerView(in view: CustomView) -> UIView {
let headerView = UIView()
headerView.backgroundColor = .green
return headerView
}
func heightForHeader(in view: CustomView) -> CGFloat {
return 150
}
}
如何绘制通过DataSource通过的标头视图?
我不知道。我感谢任何帮助。
谢谢。
通过在您的CustomView
中调用。
class CustomView: UIView {
private let headerViewTag = 42
weak var dataSource: CustomViewDatasource? {
didSet {
updateHeaderView()
}
}
private func updateHeaderView() {
// remove the old one
viewWithTag(headerViewTag)?.removeFromSuperview()
// ask for customized data
let headerView = dataSource?.headerView(in: self) ?? defaultHeaderView()
let headerViewHeight = dataSource?.heightForHeader(in: self) ?? 100
headerView?.translatesAutoresizingMaskIntoConstraints = false
headerView?.tag = headerViewTag
if let headerView = headerView {
addSubview(headerView)
// set your constraints
}
}
private func defaultHeaderView() -> UIView {
// default header view's implementation here
}
}