目的: 我想在搜索栏的文本字段中将右视图设置为标签
以下代码在ios 6中正常工作以执行相同的操作:
UISearchBar *search = [[UISearchBar alloc] init];
[search setTintColor:[UIColor grayColor]];
search.frame = CGRectMake(0, 150, 320,50);
search.delegate = self;
UITextField *searchField=[search.subviews objectAtIndex:1];//Changed this line in ios 7
searchField.backgroundColor=[UIColor redColor];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=@"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
[self addSubView:search];
当我在ios 7中运行相同的代码(xcode 7.0.2完全更新)时,它给了我错误,谷歌搜索后我的搜索栏到文本字段的层次结构已被更改,所以我修改了我的代码:
用上面的代码替换了注释行:
UITextField *searchField=[((UIView *)[search.subviews objectAtIndex:0]).subviews lastObject];
执行此操作后,它没有给我任何错误(也通过打印文本字段的描述检查日志,一切正常),当我运行它时,它给出了带有红色背景的文本字段但是未显示rightView的标签对我来说。现在,任何人都可以帮我看看如何显示这个右视图。
答案 0 :(得分:6)
如果您想以编程方式执行此操作,则必须在.h文件中声明UISearchBar
对象。
UISearchBar *searchBar;
在您的.m文件中,您可以编写如下代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
searchBar = [[UISearchBar alloc] init];
[searchBar setTintColor:[UIColor grayColor]];
searchBar.frame = CGRectMake(0, 150, 320,50);
searchBar.delegate = self;
[self.view addSubview:searchBar];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UITextField *searchField;
if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
searchField=[searchBar.subviews objectAtIndex:1];
else
searchField=[((UIView *)[searchBar.subviews objectAtIndex:0]).subviews lastObject];
searchField.backgroundColor=[UIColor redColor];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=@"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
我认为这适用于iOS7和iOS7的早期版本。
答案 1 :(得分:4)
首先,您的方法并不好,并且在iOS版本中无法维护。 我认为在将自定义视图设置为rightView属性后,UISearchBarTextField正确视图的初始化正在进行。如果在viewDidAppear方法中设置searchField.rightView,您将看到正确的结果:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UITextField *searchField=[((UIView *)[_searchBar.subviews objectAtIndex:0]).subviews lastObject];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=@"Hello";
label.textColor=[UIColor greenColor];
searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
我已经在iOS 7模拟器上对其进行了测试,但它确实有效。
答案 2 :(得分:0)
您必须先获取文本字段 无需索引子视图以获取文本字段或条形按钮。
您可以直接获取文本字段和条形按钮
在swift中
let textField = searchBar.valueForKey("searchField") as? UITextField
let cancelBarButton = searchBar.valueForKey("cancelBarButtonItem") as? UIBarButtonItem
在Objective-C
中UITextField *textField = [searchBar valueForKey:@"searchField"]:
UIBarButtonItem *cancelBarButton = [searchBar valueForKey:@"cancelBarButtonItem"]:
然后您可以使用
设置左视图和右视图textField.leftView = yourView
textField.rightView = yourView