Swift中代理的使用
和OC使用一样。
import UIKit //定义协议 protocol CollectionViewControllerDelegate : NSObjectProtocol { //定义协议方法 func clickEvent(value: String) } class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { //声明代理属性 (注:使用weak修饰, 该协议需要继承NSObjectProtocol基协议) weak var delegate : CollectionViewControllerDelegate? }
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.clickEvent(value: "点击事件") }
//在第一次实例化 CollectionViewController 的时候, 设置代理 let collectionVC = CollectionViewController() collectionVC.delegate = self //遵守代理协议 /** extension -- extension 类似于 OC 中的 Category -- 格式: extension 类名 {} -- Swift中 代码可读性差, 通过 extension 完成代码分块, 增强可读性, 单一模块单独处理, 增大了当前类的作用域 -- extension 中 可以添加计算型属性 不能添加存储型属性; 可以定义便利构造函数 不能定义指定构造函数 */ extension TableViewController : CollectionViewControllerDelegate { func clickEvent(value: String) { } }