代码之家  ›  专栏  ›  技术社区  ›  Golovanov Dmytrii

如何像UITableDataSource那样为我的类创建数据源?

  •  -3
  • Golovanov Dmytrii  · 技术社区  · 7 年前

    我需要为这个类创建数据源协议,它是在UITableView中实现的,作为UITableDataSource。

    如果你知道如何做到这一点或有链接到这个问题的解决办法,请帮助我。 谢谢大家的提问!

    2 回复  |  直到 7 年前
        1
  •  2
  •   rraphael    7 年前

    创建自定义数据源的工作方式与委托模式类似。

    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 ).

        2
  •  1
  •   Shehata Gamal    7 年前

    可能是这样的

    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 {
    
        }
    
    }