如何在SearchBar Reference中访问诸如imageview和label之类的视图?

问题描述:

我想自定义使用搜索栏参考搜索栏作为申报波纹管如何在SearchBar Reference中访问诸如imageview和label之类的视图?

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

然后,我试图访问的UIImage参考,并UISearchBarTextFieldLabel如上图

This is the picture

我使用以下代码打印子视图的参考文件

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

但没有按预期得到结果。我想要UIImage ref以及UISearchBarTextFieldLabel。我怎样才能做到这一点?

+0

您可以完全自定义:https://iosdevcenters.blogspot.com/2016/07/hacking-uisearchbar-in-swift.html –

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

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

+0

什么答案哥们。惊人! –

您可以从搜索栏达到的ImageView这样比你能达到的UIImage

Objective-C的

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

斯威夫特3斯威夫特4

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

感谢您的回答,这也是正确的。 –