iOS 代理模式三要素:
@protocol UITableViewDelegate)。@interface MyVC : UIViewController 。tableView:heightForRowAtIndexPath:)。// 必須顯式設置,否則不會回調!
tableView.delegate = self;
tableView.dataSource = self;
系統內部持有 weak 引用,運行時通過 respondsToSelector: 判斷是否實現,再發送消息調用。
| 組件 | 代理方法 | 觸發時機 |
|---|---|---|
| UITableView | heightForRowAtIndexPath | 重載數據、滾動顯示新行時 |
| UIScrollView | scrollViewDidScroll | 滾動過程中持續觸發 |
| UITextField | textFieldShouldReturn | 用戶點擊鍵盤 Return 時 |
delegate = self → 方法不調用。weak 生命週期。respondsToSelector: 返回 NO,靜默失效。iOS 13+ 可用 Combine 框架或閉包回調替代傳統代理,減少樣板代碼。