我正试图使用声明如下所示的SearchBar引用自定义SearchBar
@property (weak, nonatomic) IBOutlet UISearchBar *searchRef;然后,我尝试访问UIImage引用和UISearchBarTextFieldLabel,如图所示

我正在使用以下代码打印子视图的引用
NSLog(@"%@",self.searchRef.subviews[0].subviews[1].subviews);但没有得到预期的结果。我想要UIImage裁判和UISearchBarTextFieldLabel。我怎么能这么做?
发布于 2017-04-12 09:53:28
如果有对文本字段的引用,则可以将其转换为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's视图总是以这种方式排列。例如,Apple将来可能会决定更改视图层次结构,这可能会导致您的代码完全失败或崩溃。
如果必须这样做,则递归搜索每个视图的子视图将更安全,直到找到所要查找的内容为止,而不是硬编码数组索引。
发布于 2017-04-12 09:52:50
您可以像这样从搜索栏到达imageView,而不是到达uiimage。
目标-C
UITextField *textFieldInsideSearchBar = [self.searhBar valueForKey:@"searchField"];
UIImageView *imageView = (UIImageView *) textFieldInsideSearchBar.leftView;Swift 3和Swift 4
let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
let imageView = textFieldInsideSearchBar?.leftView as! UIImageViewhttps://stackoverflow.com/questions/43365885
复制相似问题