[英]more than one delegate listen to an instance of uisearchbar
有沒有一種方法可以讓多個對象偵聽UISearchbBar實例的void委托方法?
例如,UISearchDisplayController如何知道搜索欄的文本字符串已更改為:
– searchDisplayController:shouldReloadTableForSearchString:
同時,作為搜索顯示控制器實例的表視圖控制器可以成為搜索欄的委托,並且知道文本是否已更改?
@interface MultiplexingSearchBarDelegate : NSObject<UISearchBarDelegate> {
NSMutableArray* delegates;
}
- (void) addDelegate: (id) theDelegate;
- (void) removeDelegate: (id) theDelegate;
@end
@implementation MultiplexingSearchBarDelegate
- (id) init {
if ((self = [super init])) {
delegates = [[NSMutableArray alloc] initWithCapacity: 16];
}
}
- (void) dealloc {
[delegates release];
[super dealloc]
}
- (void) addDelegate: (id) theDelegate {
@synchronized(delegates) {
if (theDelegate && ! [delegates containsObject: theDelegate]) {
[delegates addObject: theDelegate];
}
}
}
- (void) removeDelegate: (id) theDelegate {
@synchronized(delegates) {
if (theDelegate && [delegates containsObject: theDelegate]) {
[delegates removeObject: theDelegate];
}
}
}
//add your UISearchBarDelegate methods here, following a pattern like this
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
@synchronized(delegates) {
for (id<UISearchBarDelegate> theDelegate in delegates) {
[theDelegate searchBar:searchBar textDidChange:searchText];
}
}
}
@end
然后,只需將MultiplexingSearchBarDelegate
設置為UISearchBar
的委托,然后將您的委托添加到MultiplexingSearchBarDelegate
而不是直接添加到UISearchBar
。
只能有一個對象作為委托並接收委托方法調用。 但是,委托可以根據您的喜好通知許多對象,也許通過您編寫的委托協議。 您可能需要重構一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.