LoginSignup
0
3

More than 3 years have passed since last update.

【Swift4】SearchBarの背景色を変更する(黒い線もなくす)方法

Last updated at Posted at 2019-02-21

やりたいこと

Simulator Screen Shot - iPhone 8 - 2019-02-22 at 00.49.30.png

結論

UISearchBarBackgroundを削除 or 透明化した上で、UISearchBarの色を変える。

やり方1
// UISearchBarBackgroundを取得
if let searchBarBackground = searchBar.value(forKey: "_background") as? UIImageView {
    // UISearchBarBackgroundを削除
    searchBarBackground.removeFromSuperview()
}
searchBar.backgroundColor = UIColor.red
やり方2
// UISearchBarBackgroundを取得
if let searchBarBackground = searchBar.value(forKey: "_background") as? UIImageView {
    // UISearchBarBackgroundを透明化
    searchBarBackground.alpha = 0
}
searchBar.backgroundColor = UIColor.red

コード内のvalue(forKey:)について、iOS13で禁止になったようです。
UISearchBarのプライベートなプロパティにアクセスするコードがiOS 13では禁止になったようです - Qiita

試したこと

まず試したのはこちら。

うまくいかなかった
searchBar.barTintColor = UIColor.red

このやり方だとたしかに色は変わりますが、なにやら黒い線が残ってしまいます。
Simulator Screen Shot - iPhone 8 - 2019-02-22 at 01.14.52.png

View Hierarchyで見てみると、色が変わっているのはUISearchBarBackgroundで、そこにはデフォルトで下線が引かれていることがわかりました。
スクリーンショット 2019-02-22 1.29.29.png

ならばこれはどうでしょう。

うまくいかなかった
searchBar.backgroundColor = UIColor.red

今度はUISearchBar自体の背景色が変わりましたが、UISearchBarBackgroundが挟まっているためうまくいきません(背景グレーのSearchBarとして表示されてしまいます)。
スクリーンショット 2019-02-22 1.39.53.png

最終的には、結論のようにUISearchBarBackgroundを削除 or 透明化した上で、UISearchBarの色を変えるという方法に落ち着きました。
(もっとスマートなやり方があれば、ぜひ教えてください🙂)

参考

0
3
5

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
0
3