LoginSignup
6
5

More than 5 years have passed since last update.

[Swift] UISearchBarの背景色を変える

Last updated at Posted at 2016-03-30

UISearchBarのテキストフィールド背景色を変える

スクリーンショット 2016-03-30 21.24.22.png

スクリーンショット 2016-03-30 21.23.48.png

UISearchBarのサブビュー内にTextFieldnのviewがあるので、その背景色を変えてあげる

RootViewController.swift
import UIKit

class RootViewController: UIViewController , UISearchBarDelegate{

    private var mySearchBar: UISearchBar!

    override func viewDidLoad() {
        mySearchBar = UISearchBar()
        mySearchBar.delegate = self
        mySearchBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44)
        mySearchBar.layer.position = CGPoint(x: self.view.bounds.width/2, y: 32)
        mySearchBar.tintColor = UIColor.darkGrayColor()
        mySearchBar.text = "テスト"
        // 背景色を変える
        for subView in mySearchBar.subviews {
            for secondSubView in subView.subviews {
                if secondSubView.isKindOfClass(UITextField) {
                    secondSubView.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.3)
                }
            }
        }

        self.navigationItem.titleView = mySearchBar
    }

}

参考: [stackoverflow] Cannot change search bar background color

6
5
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
6
5