如何访问SearchBar Reference中的imageview、label等视图?

How to access the view such as imageview and label in SearchBar Reference?

我正在尝试使用下面声明的 SearchBar 参考来自定义 SearchBar

@property (weak, nonatomic) IBOutlet UISearchBar *searchRef;

然后,我尝试访问 UIImage Reference 和 UISearchBarTextFieldLabel,如图所示

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

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

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

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

Objective-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,然后访问其 leftViewrightView 属性。通常,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 可能会在未来决定更改视图层次结构,这可能会导致您的代码失败或完全崩溃。

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