在Swift中更改搜索栏占位符文本字体

use*_*428 20 xcode uisearchbar uifont ios swift

我正在尝试更改搜索显示控制器中搜索栏中占位符文本的字体.我正在看一些例子,我试图实现它们,但因为它们在Objective-C中,我无法找到任何可以开始工作的例子.

例如,我试过这个:

UITextField *textField = [[searchBar subviews] objectAtIndex:1]; 
[textField setFont:[UIFont fontWithName:@"Helvetica" size:40]];
Run Code Online (Sandbox Code Playgroud)

但我无法过去 var textField: UITextField = UISearchBar

有任何想法吗?

A.G*_*A.G 32

 //SearchBar Text
    let textFieldInsideUISearchBar = dashBoardSearchBar.valueForKey("searchField") as? UITextField
textFieldInsideUISearchBar?.textColor = UIColor.whiteColor()

//SearchBar Placeholder    
     let textFieldInsideUISearchBarLabel = textFieldInsideUISearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideUISearchBarLabel?.textColor = UIColor.whiteColor()
Run Code Online (Sandbox Code Playgroud)

  • “placeholderLabel”似乎不再起作用(iOS10),但是更改“searchField”的字体也会更改占位符字体和文本字体 (2认同)

Mr.*_*ean 15

这是更改字体或searchBar文本字段中任何其他类似更改的最简单方法.我一直在使用XCode 8.4,Swift 3.x,iOS 10.x.

extension UISearchBar {

func change(textFont : UIFont?) {

    for view : UIView in (self.subviews[0]).subviews {

        if let textField = view as? UITextField {
            textField.font = textFont
        }
    }
} }
Run Code Online (Sandbox Code Playgroud)

您可以直接调用上面的代码,您可以在其中创建searchBar的IBOutlet ...

@IBOutlet weak var searchBar: UISearchBar! {
    didSet {
        searchBar.change(textFont: GlobalConstants.Font.avenirBook14)
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 14

设置占位符文本字体大小:

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)
Run Code Online (Sandbox Code Playgroud)

设置搜索文本字体大小:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)
Run Code Online (Sandbox Code Playgroud)

  • 最优雅,最正确的解决方案 (2认同)

Sou*_*har 10

searchBar.searchTextField.font = UIFont(name: "Helvetica", size: 40)
Run Code Online (Sandbox Code Playgroud)

  • 您好,欢迎来到 Stack Overflow!当您回答问题时,您应该提供某种解释,例如作者做错了什么以及您如何解决它。我告诉您这一点是因为您的答案已被标记为低质量,目前正在接受审核。您可以通过单击“编辑”按钮来[编辑]您的答案。 (2认同)

小智 8

在iOS 8中,试试这个

for subView in searchBar.subviews  {
  for subsubView in subView.subviews  {
      if let textField = subsubView as? UITextField {
        textField.attributedPlaceholder =  NSAttributedString(string:NSLocalizedString("Search", comment:""),
          attributes:[NSForegroundColorAttributeName: UIColor.orangeColor()])
      }
  }
}
Run Code Online (Sandbox Code Playgroud)


ram*_*nok 8

Swift 5 中还有一种更简单的方法:

searchBar[keyPath: \.searchTextField].font = UIFont(...)
Run Code Online (Sandbox Code Playgroud)


Aja*_*mar 6

Swift 3版@Alvin的答案

let textFieldInsideUISearchBar = searchBar.value(forKey: "searchField") as? UITextField
    let placeholderLabel       = textFieldInsideUISearchBar?.value(forKey: "placeholderLabel") as? UILabel
    placeholderLabel?.font     = UIFont.systemFont(ofSize: 12.0)
Run Code Online (Sandbox Code Playgroud)