跳到主要内容

给出委托方法的实例,并且说出UITableVIew的Data Source方法?

参考答案:

委托(Delegation)是 Objective-C 和 Swift 中的一个重要概念,允许一个对象将某些任务或责任委托给另一个对象。在 iOS 开发中,UITableView 的数据源方法就是通过委托实现的。

首先,我将给出一个简单的委托方法的实例:

// 定义一个协议,用来定义委托的方法
protocol MyDelegate: class {
    func didPressButton()
}

class MyViewController: UIViewController {
    
    weak var delegate: MyDelegate?
    
    @IBAction func buttonPressed(_ sender: Any) {
        delegate?.didPressButton()
    }
}

class AnotherViewController: UIViewController, MyDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myVC = MyViewController()
        myVC.delegate = self
        
        // 假设这里有一个按钮点击事件,当按钮被点击时,会触发 MyViewController 中的 buttonPressed 方法
    }
    
    // 实现 MyDelegate 协议中的方法
    func didPressButton() {
        print("Button was pressed!")
    }
}

在上面的代码中,MyViewController 有一个弱引用(weak reference)到其委托(delegate),当按钮被点击时,它会调用委托的 didPressButton 方法。AnotherViewController 遵循 MyDelegate 协议,并实现了其中的方法。当 MyViewController 的按钮被点击时,AnotherViewController 中的 didPressButton 方法会被调用。

接下来,我将列出 UITableView 的数据源方法:

  1. tableView(_:numberOfRowsInSection:): 返回指定分区中的行数。
  2. tableView(_:cellForRowAt:): 返回指定索引路径的单元格。
  3. numberOfSections(in:): 返回分区数。
  4. tableView(_:titleForHeaderInSection:): 返回指定分区的标题。
  5. tableView(_:titleForFooterInSection:): 返回指定分区的页脚。
  6. tableView(_:canEditRowAt:): 返回指定索引路径的行是否可以被编辑。
  7. tableView(_:commit:editingStyle:forRowAt:): 提交行的编辑更改。

这些方法都应该在遵循 UITableViewDataSource 协议的对象中实现。通常,这个对象会是你的视图控制器。