例如,您想要子类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