简体   繁体   English

更改 UISearchBar 的字体大小

[英]Change the font size of UISearchBar

如何更改UISearchBar的字体大小?

I suggest yet a different option for iOS 5.0 and up:我建议为 iOS 5.0 及更高版本提供一个不同的选项:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont systemFontOfSize:14]];

for iOS 8 (as linked by Mike Gledhill):对于 iOS 8(由 Mike Gledhill 链接):

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
            NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:20],
      }];

for iOS 9 and above:对于 iOS 9 及更高版本:

[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setDefaultTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:20]}];

This way you don't need to mess with enumerating subviews for every search bar in your app.这样你就不需要为你的应用程序中的每个搜索栏枚举子视图。

The safe way for performing this operation is as follows:执行此操作的安全方法如下:

for(UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:[UITextField class]]) {
        UITextField *searchField = (UITextField *)subView;
        searchField.font = [UIFont fontWithName:@"Oswald" size:11];
    }
}

Why is this safer than the accepted answer?为什么这比接受的答案更安全? Because it doesn't rely on the index of the UITextField staying constant.因为它不依赖于 UITextField 的索引保持不变。 (it's also a cleaner for loop) (它也是一个更清洁的 for 循环)

The accepted answer is not the recommended way of applying font for UISearchBar.接受的答案不是为 UISearchBar 应用字体的推荐方式。 Better to avoid this approach and use the answers provided by @rafalkitta or @josema.最好避免这种方法并使用@rafalkitta 或@josema 提供的答案。

But be cautious, this will be applied to all the search bars through out the app.但要小心,这将应用于整个应用程序的所有搜索栏。 In order to apply this approach to a particular search bar: create a subclass of UISearchBar and set the defaultTextAttributes on the UITextField like below为了将此方法应用于特定的搜索栏:创建UISearchBar的子类并在UITextField上设置defaultTextAttributes ,如下所示

Swift4 :斯威夫特4

    let defaultTextAttribs = [NSAttributedStringKey.font.rawValue: UIFont.boldSystemFont(ofSize: 21.0), NSAttributedStringKey.foregroundColor.rawValue:UIColor.red]
    UITextField.appearance(whenContainedInInstancesOf: [CustomSearchBar.self]).defaultTextAttributes = defaultTextAttribs

Obj-C(iOS11)对象-C(iOS11)

    UIFont *font = [UIFont boldSystemFontOfSize:21.0];
    UIColor *color = [UIColor redColor];
    NSDictionary * defaultTextAttribs = @{NSFontAttributeName:font, NSForegroundColorAttributeName: color};
    [UITextField appearanceWhenContainedInInstancesOfClasses:@[[CustomSearchBar class]]].defaultTextAttributes = defaultTextAttribs;

The UISearchBar has a UITextField inside, but there's no property to access it. UISearchBar 内部有一个 UITextField,但没有访问它的属性。 So, there is no way for doing it in a standard way.所以,没有办法以标准的方式做到这一点。

But there is a non-stardard way to workaround it.但是有一种非标准的方法来解决它。 UISearchBar inherits from UIView, you can access it's subviews using [searchBar subviews]. UISearchBar 继承自 UIView,您可以使用 [searchBar subviews] 访问它的子视图。 If you print in the console it's subviews you will see that it have these views.如果您在控制台中打印它的子视图,您将看到它具有这些视图。

UISearchBarBackground, UISearchBarTextField. UISearchBarBackground,UISearchBarTextField。

So, to change the font size you will only need to do that因此,要更改字体大小,您只需要这样做

    UITextField *textField = [[searchBar subviews] objectAtIndex:1];
[textField setFont:[UIFont fontWithName:@"Helvetica" size:40]];

But, if the UISearchBar changes in the future and the textfield isn't in the position 1 anymore, your program will crash, so it's better to check through the subviews the position of the UITextField and then set the font size.但是,如果将来 UISearchBar 发生变化并且 textfield 不再位于位置 1,则您的程序将崩溃,因此最好通过子视图检查 UITextField 的位置,然后设置字体大小。

You can use KVC (key-Value Coding) to get the textfield您可以使用 KVC(键值编码)来获取文本字段

UITextField *textField = [self.searchBar valueForKey: @"_searchField"];
[textField setTextColor:[UIColor redColor]];
[textField setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]];

In swift 2.0 for a search bar created programatically you could do this:在以编程方式创建的搜索栏的 swift 2.0 中,您可以执行以下操作:

override func layoutSubviews() {
  super.layoutSubviews()

  let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
  textFieldInsideSearchBar.font = UIFont.systemFontOfSize(20)
 }

In this case I put the code in a UIView subclass but it will work in other places too (ie viewWillAppear from the UIViewController)在这种情况下,我将代码放在 UIView 子类中,但它也可以在其他地方工作(即 UIViewController 中的 viewWillAppear)

在 swift 3 中,您可以通过以下方式实现:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont(name: "AvenirNextCondensed-Regular", size: 17.0)

You shouldn't use private API like in other answers.您不应该像其他答案一样使用私有 API。 If you want to customise search bars in whole application, you can use class's appearance proxy.如果要在整个应用程序中自定义搜索栏,可以使用类的外观代理。 It allows to modify search bar text attributes, placeholder attributes, cancel button, text field background image, background image etc. Example of use:它允许修改搜索栏文本属性、占位符属性、取消按钮、文本字段背景图像、背景图像等。 使用示例:

if #available(iOS 9.0, *) {
    let searchBarTextAttributes = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12), 
        NSForegroundColorAttributeName: UIColor.red
    ]
    // Default attributes for search text
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes

    // Attributed placeholder string
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search...", attributes: searchBarTextAttributes)

    // Search bar cancel button
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(searchBarTextAttributes, for: .normal)
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Cancel"
}

UITextField appearance does not work for UISearchBar s created programmatically. UITextField外观不适用于以编程方式创建的UISearchBar You have to use a recursive workaround您必须使用递归解决方法

- (void)viewDidLoad {
  [super viewDidLoad];
  [self recursivelySkinTextField:self.searchBar];
}

- (void)recursivelySkinTextField:(UIView *)view {
  if (!view.subviews.count) return;

  for (UIView *subview in view.subviews) {
    if ([subview isKindOfClass:[UITextField class]]) {
      UITextField *searchField = (UITextField *)subview;
      searchField.font = [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] font];
      searchField.textColor = [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] textColor];
    }
    [self recursivelySkinTextField:subview];
  }
}

I wanted to use 'Roboto-Regular' as default font for all the uisearchbars in my project.我想使用“Roboto-Regular”作为我项目中所有 uisearchbars 的默认字体。 I made an uisearchbar extension.我做了一个 uisearchbar 扩展。

extension UISearchBar {
func addRobotoFontToSearchBar(targetSearchBar:UISearchBar?) -> UISearchBar
{
    let textFieldInsideSearchBar = targetSearchBar!.valueForKey("searchField") as! UITextField
    textFieldInsideSearchBar.font = UIFont(name: "Roboto-Regular", size: 15.0)

//UIBarButtons font in searchbar
let uiBarButtonAttributes: NSDictionary = [NSFontAttributeName: UIFont(name: "Roboto-Regular", size: 15.0)!] 
UIBarButtonItem.appearance().setTitleTextAttributes(uiBarButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)

    return targetSearchBar!
}
}

Usage:用法:

self.sampleSearchBar.addRobotoFontToSearchBar(sampleSearchBar)

Rewrote Eugene's recursive solution in swift - changed the function name to more accurately describe function.在 swift 中重写了 Eugene 的递归解决方案 - 更改了函数名称以更准确地描述函数。 For my case, I needed to change the font size.就我而言,我需要更改字体大小。 This worked for me.这对我有用。

func findAndSetTextField(view: UIView) {
    if (view.subviews.count == 0){
        return
    }

    for var i = 0; i < view.subviews.count; i++ {
        var subview : UIView = view.subviews[i] as UIView
        if (subview.isKindOfClass(UITextField)){
            var searchField : UITextField = subview as UITextField
            searchField.font = UIFont(name: "Helvetica", size: 19.0)!
         }
         findAndSetTextField(subview)
    }
}

Try finding the search bar by its key:尝试按关键字查找搜索栏:

UITextField *searchField = [self.searchDisplayController.searchBar valueForKey:@"_searchField"];
searchField.font = [[UIFont fontWithName:@"Oswald" size:11];

the full code should be below:完整代码应如下:

for (UIView *v in (SYSTEM_VERSION_LESS_THAN(@"7.0")?searchBar.subviews:[[searchBar.subviews objectAtIndex:0] subviews])) {

    if([v isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)v;
        [textField setFont:fREGULAR(@"15.0")];

        return;
    }
}

我知道这是一个旧线程,但是由于 iOS 13 UISearchBar 具有 searchTextField 属性,您可以在该属性上设置所需的字体。

iOS 13+

  searchBar.searchTextField.font = UIFont(name: "YOUR-FONT-NAME", size: 13)

If you need a convenient way to change all your application searchbars, here's a simple subclass in Swift 5 :如果您需要一种方便的方法来更改所有应用程序搜索栏,这里是Swift 5 中的一个简单子类:

class MySearchBar: UISearchBar {
    override func layoutSubviews() {
        super.layoutSubviews()

        if let textFieldInsideSearchBar = value(forKey: "searchField") as? UITextField {
            textFieldInsideSearchBar.font = UIFont(name: "Oswald-Light", size: 14)
        }
    }
}

Add below code where you define or setting up your UISearchBar在您定义或设置 UISearchBar 的位置添加以下代码

Swift4 :斯威夫特4:

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.init(name: "Ubuntu-Regular", size: 16)
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.init(name: "Ubuntu-Regular", size: 16)

Objective C:目标 C:

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];

For Swift 4.2+对于 Swift 4.2+

let defaultTextAttributes = [
    NSAttributedString.Key.font: UIFont.init(name: "Ubuntu-Regular", size: 16),
    NSAttributedString.Key.foregroundColor: UIColor.gray
]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = defaultTextAttributes

iOS 13 or later: iOS 13 或更高版本:

if #available(iOS 13.0, *) {
    // set your desired font size
    self.searchBar.searchTextField.font = .systemFont(ofSize: 14.0) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM