以编程方式将搜索栏放在导航栏中

时间:2016-01-05 12:21:56

标签: ios objective-c searchbar

我正在尝试使用以下代码在导航栏中放置搜索栏:

Name      |     Document     |     Notes
Company A |    Doc A Part 1  |   
----------|------------------| Withdrawn in Jan 2016
Company A |    Doc A Part 2  |    

它会将搜索栏放在导航栏中,但不会覆盖任何一侧的按钮。它也没有取消选项。

enter image description here

我希望看起来像这样:

enter image description here

有人可以建议如何调整上面的代码吗?

提前感谢任何建议。

1 个答案:

答案 0 :(得分:0)

在我的一个项目中,我使用下面的代码做了同样的事情,希望它能帮到你:

-(void)addSearchBar{
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(35, -10, 285, 64)];
    self.navigationItem.rightBarButtonItems=nil;

    [self.searchBar setShowsCancelButton:YES];
    for (id subView in ((UIView *)[self.searchBar.subviews objectAtIndex:0]).subviews) {
        NSLog(@"subView====%@", subView);
        if ([subView isKindOfClass:[UITextField class]]) {
            UITextField *textField = subView;
            textField.keyboardAppearance = UIKeyboardAppearanceAlert;
            break;
        }
        if([subView isKindOfClass:[UIButton class]]){

            UIButton* cancelBtn = (UIButton*)subView;
            cancelBtn.frame=CGRectMake(cancelBtn.frame.origin.x, cancelBtn.frame.origin.x, 30, 30);
            [cancelBtn setTitle:@"" forState:UIControlStateNormal];
            [cancelBtn setImage:[UIImage imageNamed:@"btn_cancel_h.png"] forState:UIControlStateNormal];
            [cancelBtn setEnabled:YES];
        }
    }

    [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor whiteColor]];

            self.searchBar.delegate=self;
    [self.navigationController.navigationBar addSubview:self.searchBar];
}