我讨厌从Swift 3.1到Swift 4的所有更改。现在,我又遇到了另一个难题。我可以自定义搜索栏,但是现在我需要更改输入文本的来源和占位符。
我已经移动了天堂和大地,但找不到改变字体的解决方案。我也想将搜索图标更改为自定义图标。
Swift 4:
更改字体:
UITextField.appearance(whenContainedInInstancesOf: [CustomSearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.font.rawValue: UIFont.boldSystemFont(ofSize: 21.0)]
更改颜色:
UITextField.appearance(whenContainedInInstancesOf: [CustomSearchBar.self]).defaultTextAttributes = = [NSAttributedStringKey.foregroundColor.rawValue:UIColor.red]
搜索图标:
searchController.searchBar.setImage(UIImage(named: "search_icon"), for: UISearchBarIcon.search, state: .normal)
占位符:
UITextField.appearance(whenContainedInInstancesOf: [CustomSearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
最新最快:
let attributes = [NSAttributedString.Key.font: UIFont.regular(15), NSAttributedString.Key.foregroundColor: UIColor.black]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = attributes
尝试使用Swift 5:
searchBar[keyPath: \.searchTextField].font = UIFont(...)