如何在导航标题下添加search栏
我需要导航标题下的search栏如何以编程方式或通过故事板。
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,30, 250,44)]; searchBar.placeholder = @"Search"; UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc]initWithCustomView:searchBar]; searchBarItem.tag = 123; searchBarItem.customView.hidden = YES; searchBarItem.customView.alpha = 0.0f; self.navigationItem.leftBarButtonItem = searchBarItem; self.navigationItem.title = @"locations";
您已经将search栏添加为UIBarButtonItem
,这就是为什么它不可见。
如果要显示search栏而不是导航栏的标题视图,请使用此代码
显示导航栏代替导航标题的代码:
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]}];
输出:
更新的输出
要自定义textField:
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像素像search栏的文本字段。
这里是图像:
并输出:
希望能帮助到你 …
快乐编码…
我们也可以使用文本框作为search栏,它在我的应用程序工作正常,
转到StoryBoard
并做以下更改
从对象Library--> type view
并拖动到storyboard
并粘贴在导航栏下方。
将文本框添加到视图并分配sockets和代表。
现在去viewcontroller.m
并粘贴下面的代码
-(void)textFieldDidChange:(UITextField *)textField { searchTextString=textField.text; [self updateSearchArray:searchTextString]; } -(void)updateSearchArray:(NSString *)searchText { if(searchText.length==0) { isFilter=NO; } else { isFilter=YES; searchArray=[[NSMutableArray alloc]init]; for(NSString *string in responceArray) { NSRange stringRange = [[NSString stringWithFormat:@"%@",string] rangeOfString:searchtext.text options:NSCaseInsensitiveSearch]; if (stringRange.location != NSNotFound) { [searchArray addObject:string]; } } [jobsTable reloadData]; } }