2014-10-18 90 views
12

我試圖在搜索顯示控制器中的搜索欄中更改佔位符文本的字體。我正在看一些例子,我試圖實現它們,但是因爲它們在Objective-C中,我無法找到任何可以工作的東西。在Swift中更改搜索欄佔位符文本字體

例如,我這個嘗試之一:

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

但我無法讓過去var textField: UITextField = UISearchBar

任何想法?

回答

5

在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()]) 
     } 
    } 
} 
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。

24
//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() 
+0

「placeholderLabel」似乎沒有工作了(iOS10),但改變「searchField」的字體也改變了佔位符字體和文本字體 – Daniel 2018-01-24 10:05:37

7

這是在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 
     } 
    } 
} } 

上面的代碼可以直接在您進行搜索欄的一個IBOutlet被稱爲...

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

斯威夫特3版@阿爾文的答案

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

只是在如果您正在使用故事板,則需要在故事板的搜索欄上設置一個佔位符值,然後才能使用此代碼 – Leonardo 2017-07-13 20:36:46