搜索栏子视图不起作用,UITextField委托不为搜索栏调用的方法

时间:2013-12-19 11:18:47

标签: ios iphone objective-c ios7 uisearchbar

请参阅我的以下代码:

我的viewController中有一个搜索栏

 for (UIView *subView in  self.searchBar.subviews) 
     {
      if([subView conformsToProtocol:@protocol(UITextInputTraits)]) 
       {      
        [(UITextField *)subView setDelegate:self];
        [(UITextField *)subView setReturnKeyType:UIReturnKeyDefault];
        [(UITextField *)subView setBackground:[UIImage imageNamed:@"shopping-Search"]];
      }
    }

for (UIView *subview in self.searchBar.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}

此代码在iOS 6中运行良好,但在iOS 7中无效。

1 个答案:

答案 0 :(得分:3)

在iOS7中更改了searchBar子视图层次结构,请尝试以下操作:

<强> iOS7:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];

iOS6及之前:

NSArray *searchBarSubViews =  self.searchBar.subviews;

尝试以下更新功能:

for (UIView *subView in searchBarSubViews) {
      if([subView conformsToProtocol:@protocol(UITextInputTraits)]) 
       {      
        [(UITextField *)subView setDelegate:self];
        [(UITextField *)subView setReturnKeyType:UIReturnKeyDefault];
        [(UITextField *)subView setBackground:[UIImage imageNamed:@"shopping-Search"]];
      }
}

for (UIView *subview in searchBarSubViews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}