如何在 Swift 中构建和使用我自己的数据源协议?

How to build and use my own datasource protocol in Swift?

我想为用户提供自定义视图组件库的 header 视图的选项。

所以我想遵循 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 的 header 视图?

我不知道。如果有任何帮助,我将不胜感激。

谢谢。

通过在您的 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
    }

}