在navigationBar上添加searchBar 并设置字体

本文介绍如何在iOS应用的navigationBar上添加searchBar,并详细说明在页面跳转时正确处理searchBar的显示与移除,确保它只在特定页面显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//添加搜索框
- (void)addSearchBar{
    CGRect mainViewBounds = self.navigationController.view.bounds;
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(CGRectGetWidth(mainViewBounds)/2-((CGRectGetWidth(mainViewBounds)-120)/2), CGRectGetMinY(mainViewBounds)+27, CGRectGetWidth(mainViewBounds)-100, 30)];
    _searchBar.delegate = self;
    _searchBar.showsCancelButton = NO;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchBar.returnKeyType=UIReturnKeySearch;
    _searchBar.placeholder = @"编号/申请人/所在部门";

    //修改placeholder 字体
    UITextField * searchField = [_searchBar valueForKey:@"_searchField"];
    [searchField setValue:kSubTextColor forKeyPath:@"_placeholderLabel.textColor"];
    [searchField setValue:[UIFont boldSystemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
}

注意:在跳转页面的时候必须移除掉,否则,会在下个页面继续显示,在页面出现时再添加上

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //添加搜索框
    [self.navigationController.view addSubview: _searchBar];
}

- (void)viewWillDisappear:(BOOL)animated{
    [_searchBar resignFirstResponder];
    [_searchBar removeFromSuperview];
}

从页面显示上来看,searchBar添加在了searchBar 上,实际上添加在了当前页的View上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值