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

时间:2019-02-22 16:42:35

标签: ios swift datasource

我想给用户一个选项来定制我的自定义视图组件库的标题视图。

所以我想遵循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
  }
}

如何绘制数据源传递的标题视图?

我不知道。我将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

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

}