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

时间:2014-10-18 16:25:03

标签: ios xcode swift uisearchbar uifont

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

例如,我试过这个:

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

但我无法超越var textField: UITextField = UISearchBar

有什么想法吗?

8 个答案:

答案 0 :(得分: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()

答案 1 :(得分:14)

这是更改字体或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
        }
    }
} }

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

@IBOutlet weak var searchBar: UISearchBar! {
    didSet {
        searchBar.change(textFont: GlobalConstants.Font.avenirBook14)
    }
}

答案 2 :(得分:9)

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

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)

设置搜索文本字体大小:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.systemFont(ofSize: 12)

答案 3 :(得分: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()])
      }
  }
}

答案 4 :(得分:6)

@ Alvin的答案的Swift 3版本

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

答案 5 :(得分:5)

searchBar.searchTextField.font = UIFont(name: "Helvetica", size: 40)

答案 6 :(得分:3)

这适用于ios7 - > ios9使用swift 2:

if #available(iOS 9.0, *) {
    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).font = UI.getInstance.tinyFont
} else {
    func checkSubview(view:UIView)
    for subView in view.subviews {
        if subView is UITextField {
            let textField = subView as! UITextField
            textField.font = UI.getInstance.tinyFont
        } else {
            checkSubview(subView)
        }

    }
    checkSubview(view)
}

只需用您想要的任何字体替换UI.getInstance.tinyFont。

答案 7 :(得分:2)

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

searchBar[keyPath: \.searchTextField].font = UIFont(...)