无法在ios 7中的搜索栏的文本字段中设置rightview或leftview

Meh*_*kar 0 textfield uisearchbar ios7 rightview

目的:我想在搜索栏的文本字段中将右视图设置为标签

以下代码在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];
Run Code Online (Sandbox Code Playgroud)

当我在ios 7中运行相同的代码(xcode 7.0.2完全更新)时,它给了我错误,谷歌搜索后我的搜索栏到文本字段的hiearchy已被更改,所以我修改了我的代码:

用以下代码替换上面代码中的注释行:

UITextField *searchField=[((UIView *)[search.subviews objectAtIndex:0]).subviews lastObject];
Run Code Online (Sandbox Code Playgroud)

在这之后,它没有给我任何错误(也通过打印文本字段的描述检查日志,一切都运行良好),当我运行它时,它给出了带有红色背景的文本字段,但是右边的标签没有显示给我.现在,任何人都可以帮助我如何显示这个右视图.

Yuv*_*inh 6

如果要以编程方式执行此操作,则必须UISearchBar在.h文件中声明对象.

UISearchBar  *searchBar;
Run Code Online (Sandbox Code Playgroud)

在您的.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;
}
Run Code Online (Sandbox Code Playgroud)

我认为这适用于iOS7和iOS7的早期版本.