如何在SearchBar参考中访问图像视图和标签等视图?

时间:2017-04-12 09:40:45

标签: ios searchbar subviews

我正在尝试使用SearchBar引用自定义SearchBar,如下所示

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

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

This is the picture

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

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

但没有按预期得到结果。我想要UIImage引用以及UISearchBarTextFieldLabel。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您可以从搜索栏中访问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! UIImageView

答案 1 :(得分:0)

如果您对文本字段有引用,则可以将其转换为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可能会在将来决定更改视图层次结构,这可能会导致代码失败或完全崩溃。

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