2015-01-20 105 views
9

我現在正在爲此苦苦掙扎。到處搜索,但提供的解決方案只適用於Objective-C。其中包括在更改UISearchBar的textField背景

UITextField *txt = [_searchBar valueForKey:@"_searchField"];

雖然有些人可能會說,這是受保護的API和蘋果公司可能會拒絕這樣的代碼的應用程序。

所以,現在我已經嘗試了很多方法來解決這個問題,它根本就不工作。 我的代碼是這樣的:

searchBar = UISearchBar(frame: CGRectMake(0, 0, 320.0, 30.0)) 
searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth 
searchBar.searchBarStyle = UISearchBarStyle.Minimal 
searchBar.layer.cornerRadius = 15 
searchBar.delegate = self 

searchBar.backgroundColor = UIColor.whiteColor() 

if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1{ 
    // Load resources for iOS 6.1 or earlier 
    searchBar.placeholder = "Search"; 
} else { 
    // The following "hack" (if we can call that) breaks the UI for different size devices. 
    // Load resources for iOS 7 or later 
    searchBar.placeholder = "Search           "; 
} 

這讓我奇怪的結果: enter image description here

而我想要的只是該的UISearchBar裏面的文本框有一個白色的背景和搜索欄本身具有的cornerRadius ,說,15.

我該怎麼做?

在此先感謝

+0

的UITextField * searchField = [SearchBar valueForKey:@「_ searchField」]; searchField.textColor = [UIColor whiteColor]; 我已經在我的應用程序和應用程序中使用此代碼,它已經在App Store中可用。 – Bhoomi 2015-04-04 05:42:55

回答

22

這麼多,你要訪問的UITextField的裏面的UISearchBar。你可以通過使用 valueForKey("searchField")

var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField 

textFieldInsideSearchBar?.textColor = yourcolor 
textFieldInsideSearchBar?.backgroundColor = backgroundColor 
... 

那裏你可以改變一樣的的UITextField

+10

您應該將樣式設置爲'Prominent'或'Default.'如果您喜歡使用'Minimal','backgroundColor'不起作用。 'searchBar.searchBarStyle = UISearchBarStyle.Prominent // or .Default' – fatihyildizhan 2016-01-04 16:17:31

+1

@fatihyildizhan謝謝這對於不使用最小風格確實非常重要!花了太多的時間在這.... – Altimac 2016-06-17 14:46:07

8

添加到上面的回答文字顏色或任何的backgroundColor參數。 如果你想保留搜索欄樣式UISearchBarStyleMinimal和改變的UISearchBar的文本框的背景下,文本框的的borderStyle設置爲UITextBorderStyleNone

目標C:

self.searchBar.searchBarStyle = UISearchBarStyleMinimal; 

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"]; 
    txfSearchField.borderStyle = UITextBorderStyleNone; 
    txfSearchField.backgroundColor = yourColor; 
+0

我已經搜索周圍。這是真正有效的解決方案! – flame3 2017-03-29 17:04:34

+0

我同意。此解決方案在'UISearchBarStyle'設置爲'.minimal'時有效。測試iOS 10.3 – yohannes 2017-04-08 06:46:26

+0

它的工作原理,但爲什麼? – 2018-01-20 13:29:49

7

在斯威夫特3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { 
     txfSearchField.borderStyle = .none 
     txfSearchField.backgroundColor = .lightGray 
    }