例如,您想要子類UIScrollView
創建UITableView
,並且您不想使用任何專用接口。爲需要使用委託的類創建子類
爲了加載單元格,您必須使用父級代理(scrollViewDidScroll
,UIScrollViewDelegate
)。另外,您想將一些自己的方法添加到委託中(例如tableView:willDisplayCell:forRowAtIndexPath:
)。
我現在要做的是:
- 創建
UITableViewDelegate
協議延伸UIScrollViewDelegate
協議。 創建
UITableViewDelegateProxy
,我設置爲super.delegate
,在UITableView
的init
。此類符合
UIScrollViewDelegate
並具有next
屬性,該屬性可以參考對象符合UITableViewDelegate
。默認情況下,它會嘗試使用自己的實現進行響應。如果不可用,它會嘗試使用
next
的實現,否則它不會響應。- (BOOL)respondsToSelector:(SEL)aSelector { if ([super respondsToSelector:aSelector]) return YES; else if (self.next) return [self.next respondsToSelector:aSelector]; else return NO; } - (void)forwardInvocation:(NSInvocation *)anInvocation { // self did not respond to selector if (self.next) [anInvocation invokeWithTarget:self.next]; else [self doesNotRecognizeSelector:anInvocation.selector]; }
所以到現在爲止,如果
UIScrollViewDelegate
擴展這個類是完全透明的,面向未來的。然後,添加實施方案對於一些委託方法來改變默認行爲或添加一些更多的行爲(例如,呼叫在
scrollViewDidScroll
next
的tableView:willDisplayCell:forRowAtIndexPath:
)。覆蓋
delegate
和setDelegate:
在UITableView
返回並設置super.delegate.next
而不是super.delegate
。我也將協議從UIScrollViewDelegate
更改爲UITableViewDelegate
。
如果UIScrollView
直接通過它的ivar訪問委託,這可以正常工作。如果它使用getter,它將不會返回我們的代理,而是返回該類的用戶設置的委託。無論哪種方式,我們都不能依賴這種行爲。 (fyi:在UIScrollView
中,有時經過吸氣劑,但並不總是)。
所以,如果我們留在這個例子中,問題是:我們如何才能像我們今天一樣實現UITableView,,我們自己?
看到這個問題: http://stackoverflow.com/questions/11478740/shared-uitableviewdelegate – Lance 2012-07-16 18:45:01