Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active July 8, 2018 01:05
Show Gist options
  • Save KentarouKanno/86164c363bdb267a31f4e5818245239a to your computer and use it in GitHub Desktop.
Save KentarouKanno/86164c363bdb267a31f4e5818245239a to your computer and use it in GitHub Desktop.
UISearchBar

UISearchBar

★ フォントの色を変更する(viewDidAppeearで設定する必要あり。早すぎると反映されない 👇のタイミングでもOK)

// TextFieldを取得
let serchField = searchBar.value(forKey: "searchField") as? UITextField
serchField?.textColor = .red
class ViewController: UISearchControllerDelegate, UISearchResultsUpdating {
    
    func updateSearchResults(for searchController: UISearchController) {
        let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = .red
    }
}

★ Placeholderを設定する

searchBar.placeholder = "Search Tag"

★ キャンセルボタンの文字列を変更する

import UIKit

class ViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating {
    
    var searchController = UISearchController()

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup() {
        searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        self.navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = true
    }
    
    func updateSearchResults(for searchController: UISearchController) {
        
        searchController.searchBar.showsCancelButton = true
        if let cancelButton = searchController.searchBar.value(forKey: "cancelButton") as? UIButton {
            cancelButton.setTitle("キャンセル", for: .normal)
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment