iOS delegation

Think of a UIViewController that you’ve subclassed (call it ViewController) to manage a UICollectionView. ViewController includes a UICollectionView instance (call it collectionView). You set the collectionView instance’s delegate property to self and self is ViewController.

ViewController adopts the UICollectionViewDelegate protocol. The delegate is ViewController. To conform to the UICollectionViewDelegate protocol, ViewControllerimplements methods like collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath).

By implementing the didSelectItemAt method, ViewController gets informed of taps on UICollectionViewCell objects. When a cell is tapped, the ViewController implementation of didSelectItemAt is called. You get to define the body of the didSelectItemAt method so that, for example, when a cell is tapped, you can visually highlight the cell and perform some application-specific logic. collectionView has delegated the responsibility of handling taps on UICollectionViewCell objects to ViewController.

通过实现 didSelectItemAt 方法,当用户点击 UICollectionViewCell 对象时,ViewController 会得到通知。当一个cell被点击,ViewController 的 didSelectItemAt 方法里的实现会被调用。你需要实现didSelectItemAt方法里的内容,这样一来,例如,当一个cell被点击,你就能使这个cell高光显示并且执行一些程序逻辑。collectionView 就把处理UICollectionViewCell 对象上点击事件的责任代理给了ViewController。





转自:Understanding Delegates and Delegation in Swift 4

你可能感兴趣的:(iOS delegation)