我有一个GraphView(xib + class)类。带有标签和其他UI元素的图表视图。 我需要为此类创建DataSource协议,该协议已在UITableView中实现为UITableDataSource。 这就需要更舒适地处理数据,我希望将其加载到GraphView中。
如果您知道该怎么做或有此问题解决方案的链接,请帮助我。 谢谢所有问题!
答案 0 :(得分:2)
创建自定义数据源就像代理模式一样。
protocol GraphViewDataSource: class {
func numberOfRow(for graph: GraphView) -> Int
}
class GraphView {
weak var dataSource: GraphViewDataSource?
init() {
let numberOfRow = dataSource?.numberOfRow(for: self)
}
}
注意:不要忘记将dataSource
属性设置为weak
以避免引用周期(这就是GraphViewDataSource
需要限制为class
的原因)。< / p>
答案 1 :(得分:1)
类似于
protocol GraphDataSource {
func Graph(_ graph:GraphView , row:Int)->UIView
}
protocol GraphDelegate {
func Graph(_ graph:GraphView ,didSelect row:Int)
}
class GraphView:UIView {
weak open var dataSource:GraphDataSource?
weak open var delegate:GraphDelegate?
func configureHere() {
let v = dataSource?.Graph(self, row: 0)
delegate?.Graph(self, didSelect: 0)
}
}
class ViewController: UIViewController , GraphDataSource , GraphDelegate {
let g = GraphView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
g.delegate = self
g.dataSource = self
}
func Graph(_ graph: GraphView, didSelect row: Int) {
}
func Graph(_ graph: GraphView, row: Int) -> UIView {
}
}