您已将搜索栏添加为UIBarButtonItem,这就是它不可见的原因。
如果要显示搜索栏来代替导航栏的标题视图,请使用此代码
显示导航栏代替导航标题的代码:
UISearchBar *searchBar = [[UISearchBar alloc]init];
searchBar.tintColor = [UIColor grayColor];
searchBar.backgroundColor = [UIColor redColor];
searchBar.placeholder = @"Search";
self.navigationItem.titleView = searchBar;
输出:
在导航栏下方显示导航栏的代码:
UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];
更新:
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;
UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
输出:
更新的输出
自定义文本字段:
UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 64)];
searchBar1.tintColor = [UIColor grayColor];
searchBar1.searchBarStyle = UISearchBarStyleMinimal;
searchBar1.backgroundColor = [UIColor redColor];
searchBar1.placeholder = @"Search";
[self.view addSubview:searchBar1];
[searchBar1 setSearchFieldBackgroundImage:[UIImage imageNamed:@"text-input.png"] forState:UIControlStateNormal];
我使用的图像高度为 30 像素,类似于搜索栏的文本字段。
这是图片:
然后输出:
希望对您有所帮助...
编码愉快...