Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在搜索栏参考中访问视图,如imageview和label?_Ios_Searchbar_Subviews - Fatal编程技术网

Ios 如何在搜索栏参考中访问视图,如imageview和label?

Ios 如何在搜索栏参考中访问视图,如imageview和label?,ios,searchbar,subviews,Ios,Searchbar,Subviews,我正试图使用下面声明的SearchBar引用自定义SearchBar @property (weak, nonatomic) IBOutlet UISearchBar *searchRef; 然后,我尝试访问UIImage引用和UISearchBarTextFieldLabel,如图所示 我正在使用以下代码打印子视图的引用 NSLog(@"%@",self.searchRef.subviews[0].subviews[1].subviews); 但是没有得到预期的结果。我想要UIImage

我正试图使用下面声明的SearchBar引用自定义SearchBar

@property (weak, nonatomic) IBOutlet UISearchBar *searchRef;
然后,我尝试访问UIImage引用和UISearchBarTextFieldLabel,如图所示

我正在使用以下代码打印子视图的引用

NSLog(@"%@",self.searchRef.subviews[0].subviews[1].subviews);

但是没有得到预期的结果。我想要UIImage参考以及UISearchBarTextFieldLabel。我该怎么做呢?

您可以像这样从搜索栏访问imageView,而不是uiimage

目标-C

UITextField *textFieldInsideSearchBar = [self.searhBar valueForKey:@"searchField"];
UIImageView *imageView = (UIImageView *) textFieldInsideSearchBar.leftView;
Swift 3Swift 4

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
let imageView = textFieldInsideSearchBar?.leftView as! UIImageView

如果有对文本字段的引用,可以将其转换为
UITextField
,然后访问其
leftView
rightView
属性。通常,
leftView
是放大镜
UIImageView

UITextField *textField = (UITextField *)self.searchRef.subviews[0].subviews[1];

// Change the search image.
if ([textField.leftView isKindOfClass:[UIImageView class]]) {

    UIImageView *searchImageView = (UIImageView *)textField.leftView;

    // Do something with the image view here...
}
作为旁注,不建议假定
UISearchBar的
视图总是这样布置的。例如,苹果可能决定在将来更改视图层次结构,这可能会导致您的代码失败或完全崩溃


如果必须这样做,则递归搜索每个视图的子视图,直到找到要查找的内容,而不是对数组索引进行硬编码,这样会更安全。

多好的答案啊。太神了