LoginSignup
17
11

More than 5 years have passed since last update.

【iOS】UISearchBarのbackgroundカラーを変更する

Last updated at Posted at 2017-08-20

検索バーでよく利用するUISearchBarを自分で指定したbackgroundカラーにカスタマイズする方法です。

単純に、以下のように記述するとなぜか反映されません。

searchBar.backgroundColor = UIColor.yellow

changeBackground.png

また、barTintColorを変更するとbackgroundカラーは変更されますが、borderは残ったままになります。

searchBar.barTintColor = UIColor.yellow

barTintColor.png

そこで色々調べてみたところ、UISearchBarにはbackgroundImageが設定されているというのがわかりました。
UISearchBarBackgroundという、独自のクラスのようです。

そのため、このbackgroundImageを削除してみると無事にbackgroundColorをカスタマイズすることができました。

let barImageView = searchBar.value(forKey: "_background") as! UIImageView
barImageView.removeFromSuperview()

searchBar.backgroundColor = UIColor.yellow

removeImage.png

同様に "value(forKey: )" を利用すればTextFieldの取得もできます。

let textField = searchBar.value(forKey: "_searchField") as! UITextField

textField.backgroundColor = UIColor.blue

textField.png

textFieldを取得すれば後は、textFieldの設定を変更してカスタマイズすることができます。

ちなみにこのkeyはデバッグで内容を知ることができます。

searchBarKey.png

17
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
11