60
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UISearchBarのカスタマイズ

Last updated at Posted at 2016-09-27

iOS13では禁止になっているようです。
UISearchBarのプライベートなプロパティにアクセスするコードがiOS 13では禁止になったようです


#下準備

##ブラー無効化

extension UISearchBar {
  func disableBlur() {
    backgroundImage = UIImage()
    translucent = true
  }
}

##textField取得

extension UISearchBar {
  var textField: UITextField? {
    return valueForKey("_searchField") as? UITextField
  }
}

##アクセサリ取得

extension UITextField {
 //クリアボタン
  var rightButton: UIButton? {
    return valueForKey("_clearButton") as? UIButton
  }
 //虫眼鏡
  var lupeImageView: UIImageView? {
    return leftView as? UIImageView
  }
}

##ViewのRenderingModeをalwaysTemplateに変更

extension UIButton {
  func becomeImageAlwaysTemplate() {
    if let image = imageForState(.Highlighted) {
      let paintedImage = image.imageWithRenderingMode(.AlwaysTemplate)
      setImage(paintedImage, forState: .Normal)
      setImage(paintedImage, forState: .Highlighted)
    }
  }
}

extension UIImageView {
  func becomeImageAlwaysTemplate() {
    image = image?.imageWithRenderingMode(.AlwaysTemplate)
  }
}

#カスタマイズ

角丸

searchBar.textField.layer.cornerRadius = searchBar.textField.bounds.height / 2.0
searchBar.textField.layer.masksToBounds = true

毎回masksToBoundsを設定する必要あり

##背景色透過

searchBar.disableBlur()
searchBar.backgroundColor = UIColor.clearColor()

##placeholderの文字色変更

searchBar.placeholder = placeholder
searchBar.textField?.attributedPlaceholder = NSAttributedString(string: searchBar.placeholder ?? "", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])

##入力部分の背景色変更

searchBar.textField?.backgroundColor = UIColor.redColor()

##入力文字色変更

searchBar.textField?.textColor = UIColor.blackColor()

##クリアボタンの色変更

searchBar.textField?.rightButton?.becomeImageAlwaysTemplate()
searchBar.textField?.rightButton?.tintColor = UIColor.whiteColor()

##虫眼鏡アイコンの色変更

searchBar.textField?.lupeImageView?.becomeImageAlwaysTemplate()
searchBar.textField?.lupeImageView?.tintColor = UIColor.whiteColor()

##カーソル・選択範囲色の変更

searchBar.tintColor = UIColor.whiteColor()
60
48
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
60
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?