zoukankan      html  css  js  c++  java
  • 关于“代理”(delegate)我的一点浅见

    代理就是你这个ViewController作为一个class本来不是干这个的,却要越俎代疱完成人家别的ViewController或者程序模块(比如 AVAudioPlayer)的功能,这时候就要用代理。

    比如View里面内置一个TableView,它View既要完成View的功能,也要完成TableView的功能,它就得是 UITableViewDelegate 和 UITableViewDataSource

    然后在 ViewDidLoad 里面,或者把 delegate 设置为 self (某某TableView.delegate = self) ,dataSource 设置为 self (某某TableView.dataSource = self);或者给tableView代码单独取一个文件名,dataSource代码单独取一个文件名。然后

    class TableViewController: UITableViewController {

            let myDataSource = MyTableViewDataSource(happyThings: ["Youtube", "Github", "Nucakola"], cellIdentifier: "cell")

            let myDelegate = MyTableViewDelegate()

            override func viewDidLoad() {

            。。。。。。

    }

    在另外的两个文件里:

    class MyTableViewDelegate: NSObject, UITableViewDelegate {

    }

    class MyTableViewDataSource: NSObject, UITableViewDataSource {

            var happyThings: [AnyObject]

            var cellIdentifier: String

            let header = "Happy Things"

            init(happyThings: [AnyObject]!, cellIdentifier: String!) {

                     self.happyThings = happyThings

                     self.cellIdentifier = cellIdentifier

            }

            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

                     return HappyThings.count

            }

            func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

                      let cell = tableview.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! UITableViewCell

                      // 提取对应行数据

                      let item = HappyThings[indexPath.row]

                      // 设置 cell

                      cell.textLabel?.text = item as? String

                      return cell

            }

    }

  • 相关阅读:
    华硕路由器修改 Hosts 以达到局域网内自定义解析
    一款开源、高颜值的终端terminus,支持Windows、MacOS
    Windows 10启用Linux子系统(WSL)
    一款全能的下载工具Motrix,支持BT、磁力链、百度网盘等资源
    ubuntu 14.04 和16.04 快速下载
    CentOS 7一键安装Seafile搭建私有云存储
    background背景色
    3d爱心代码
    Mac Mini(late 2014) 添加NVMe固态组Fusion Drive
    member access within misaligned address 0x0000002c3931 for type 'struct ListNode‘
  • 原文地址:https://www.cnblogs.com/guozai9527/p/6373002.html
Copyright © 2011-2022 走看看