自定义 UISearchbar 的 UITextfield - iOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12967291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Customize UITextfield of the UISearchbar - iOS
提问by DesperateLearner
I'm trying to customize the textfield for the UISearchbar. The picture below shows my half done work.
我正在尝试为 UISearchbar 自定义文本字段。下图显示了我完成了一半的工作。
I have subclasses the UISearchbar and called it from my view controller. I'm trying to remove those dark gray lines from the textfield. Below is the implementation of the UISearchbar adding to subview of the viewcontroller.
我有 UISearchbar 的子类,并从我的视图控制器中调用它。我正在尝试从文本字段中删除那些深灰色线条。下面是添加到视图控制器子视图的 UISearchbar 的实现。
searchbar = [[SearchBar alloc] initWithFrame:CGRectMake(35,78, 250, 17)];
searchbar.backgroundColor = [UIColor clearColor];
searchbar.layer.borderColor = [[UIColor clearColor] CGColor];
searchbar.layer.borderWidth = 0;
for(UIView *view in searchbar.subviews){
if([view isKindOfClass:[UITextField class]]){
UITextField *tf= (UITextField *)view;
tf.layer.borderColor = [[UIColor clearColor] CGColor];
tf.delegate = self;
break;
}
}
[self.view addSubview:searchbar];
searchbar.delegate = self;
UISearchBar subclass:
UISearchBar 子类:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)layoutSubviews{
UITextField *searchField;
[[[self subviews] objectAtIndex:0] removeFromSuperview];
[self setTintColor:[UIColor clearColor]];
self.clipsToBounds = YES;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++) {
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) {
searchField = [self.subviews objectAtIndex:i];
searchField.leftViewMode = UITextFieldViewModeNever;
searchField.backgroundColor = [UIColor clearColor];
}
}
if(!(searchField == nil)) {
searchField.backgroundColor = [UIColor clearColor];
searchField.textColor = [UIColor blackColor];
searchField.frame = CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height-10);
[searchField setBorderStyle:UITextBorderStyleRoundedRect];
}
[super layoutSubviews];
}
I'm trying to achive something like this: The textfield should not have any boundaries. The icons are flattened UIImageView.
我正在尝试实现这样的目标:文本字段不应有任何边界。图标是扁平化的 UIImageView。
回答by Animesh
This is an easy way to get textfield from UISearchBar subview hierarchy and set its properties as needed like
这是从 UISearchBar 子视图层次结构中获取文本字段并根据需要设置其属性的一种简单方法,例如
UITextField *txfSearchField = [searchbar valueForKey:@"_searchField"];
[txfSearchField setBackgroundColor:[UIColor whiteColor]];
[txfSearchField setLeftView:UITextFieldViewModeNever];
[txfSearchField setBorderStyle:UITextBorderStyleRoundedRect];
txfSearchField.layer.borderWidth = 8.0f;
txfSearchField.layer.cornerRadius = 10.0f;
txfSearchField.layer.borderColor = [UIColor clearColor].CGColor;
回答by Nick H247
Use the following if you don't want to use undocumented features or use an image:
如果您不想使用未记录的功能或使用图像,请使用以下内容:
CGSize size = CGSizeMake(30, 30);
// create context with transparent background
UIGraphicsBeginImageContextWithOptions(size, NO, 1);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,30,30)
cornerRadius:2.0] addClip];
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.searchBar setSearchFieldBackgroundImage:image forState:UIControlStateNormal];
回答by Luke Redmore
For those still looking for an answer, Apple has added the searchTextField
property to UISearchBar in iOS 13. searchTextField
is a UISeachTextFieldwhich inherits from UITextField.
对于那些仍在寻找答案的人,ApplesearchTextField
在 iOS 13 中向 UISearchBar添加了该属性。searchTextField
是一个继承自 UITextField的UISeachTextField。
let searchBar = UISearchBar()
var searchField : UITextField
if #available(iOS 13.0, *) {
searchField = searchBar.searchTextField
} else {
searchField = //One of the other methods listed
}
回答by marmor
Starting from IOS-5 you have the appearance proxy, see: http://developer.apple.com/library/ios/#documentation/uikit/reference/UISearchBar_Class/Reference/Reference.html(there are two sections called "Customizing Appearance", check both).
从 IOS-5 开始,您有外观代理,请参阅:http: //developer.apple.com/library/ios/#documentation/uikit/reference/UISearchBar_Class/Reference/Reference.html(有两个部分称为“自定义外观”,检查两者)。
Here's a working example, it modifies all UISearchBars in the app:
这是一个工作示例,它修改了应用程序中的所有 UISearchBars:
[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"text_box"] forState:UIControlStateNormal];
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"search_icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
mysearchBar.tintColor = [UIColor whiteColor];
回答by isair
Implementation Change Resistant & High Performance
实现抗变化和高性能
To anyone reading this and wondering how the text field of a search bar can easily be accessed in Swift; you can extend UISearchBarto add a textFieldproperty by using the following piece of code which is resistant to underlying implementation changes and caches the found result so it is high performance.
对于任何阅读本文并想知道如何在 Swift 中轻松访问搜索栏的文本字段的人;您可以使用以下代码扩展UISearchBar以添加textField属性,该代码可以抵抗底层实现更改并缓存找到的结果,因此它具有高性能。
import UIKit
private var foundTextFieldAssociationKey = UInt8()
extension UISearchBar {
var textField: UITextField {
get {
let value = objc_getAssociatedObject(self, &foundTextFieldAssociationKey) as? UITextField
if value == nil {
let findInView = (UIView) -> UITextField? = { view in
for subview in view.subviews {
if let textField = (subview as? UITextField) ?? findInView(subview) {
return textField
}
}
return nil
}
guard let foundTextField = findInView(self) else {
fatalError("UISearchBar doesn't seem to have a UITextField anywhere in the view hierarchy")
}
textField = foundTextField
return foundTextField
}
return value!
}
set {
objc_setAssociatedObject(self, &foundTextFieldAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
}
If you wish to change the name of the property, make sure you don't change it to searchField. That will mess your search bar up.
如果您希望更改属性的名称,请确保不要将其更改为searchField。那会弄乱你的搜索栏。
回答by Baran Emre
iOS 13.x & Swift 5.x:
iOS 13.x 和 Swift 5.x:
Do the following to access the UITextField
in UISearchBar
.
执行以下操作以访问UITextField
in UISearchBar
。
extension UISearchBar {
/// Returns the`UITextField` that is placed inside the text field.
var textField: UITextField {
if #available(iOS 13, *) {
return searchTextField
} else {
return self.value(forKey: "_searchField") as! UITextField
}
}
}
回答by msjulie
I have found for iOS 10 I need to do this (borrowed from above and adapted quickly)
我发现对于 iOS 10 我需要这样做(从上面借来并快速适应)
extension UISearchBar {
var textField: UITextField? {
func findInView(_ view: UIView) -> UITextField? {
for subview in view.subviews {
print("checking \(subview)")
if let textField = subview as? UITextField {
return textField
}
else if let v = findInView(subview) {
return v
}
}
return nil
}
return findInView(self)
}
}
回答by Abhishek Bedi
Short and Simple
简短而简单
extension UISearchBar {
var textField:UITextField {
guard let txtField = self.value(forKey: "_searchField") as? UITextField else {
assertionFailure()
return UITextField()
}
return txtField
}
}
回答by touti
Now in iOS 13 you have searchTextField
property to directly access the text field.
现在在 iOS 13 中,您可以searchTextField
直接访问文本字段。