iPhone SDK:无法从SearchBar访问TextField

时间:2014-09-05 06:29:51

标签: ios iphone uisearchbar

我创建了一个带有Cancle按钮的自定义搜索栏。我想启用 取消 按钮 Everytime。但是只有在我开始编辑搜索栏后才能启用。 我写了以下代码。

#pragma mark - Search Bar Methods

-(void)addSearchBar{

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 65, 320, 44)];
    [self.view addSubview:self.searchBar];
    self.searchBar.showsCancelButton = YES;
    self.searchBar.delegate = self;

  for (UIView *searchBarSubview in [self.searchBar subviews]) {    
    if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {    
      @try {
        // set style of keyboard
        [(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];

        // always force return key to be enabled
        [(UITextField *)searchBarSubview setEnablesReturnKeyAutomatically:NO];
      }
      @catch (NSException * e) {        
        // ignore exception
      }
    }
  }



}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    [self.searchBar removeFromSuperview];
    [btnSearch setEnabled:TRUE];

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [self.searchBar resignFirstResponder];

}

但是我无法从其子视图中获取textField。 请帮助。

1 个答案:

答案 0 :(得分:1)

尝试使用此代码从搜索栏获取文本字段

for (UIView *subView in self.searchBar.subviews){
        for (UIView *searchView in subView.subviews){
            if ([searchView isKindOfClass:[UITextField class]])
                {

                [(UITextField *)searchView setKeyboardAppearance:UIKeyboardAppearanceAlert];
                [(UITextField *)searchView setEnablesReturnKeyAutomatically:NO];
                break;
                }
        }
    }