0
class TestViewController: UIViewController, UISearchBarDelegate {

  @IBOutlet weak var mySearchBar: UISearchBar!
  var myOwnInputView = UIView(frame: CGRectMake(100,100,50,50))

  overide func viewDidLoad() {
    mySearchBar.delegate = self
    mySearchBar.inputView = myOwnInputView // errors - "Cannot assign to the result of this expression
  }

}

I'm trying to assign a custom input view to my search bar, however based on apple documentation (-sorry could not find link anymore), for UISearchBar it seems to be a read-only value. Looking at this post, it appears that UISearchbar has multiple subviews and I need to get to the UITextField part in order to change the inputview. However, I'm not sufficiently familiar with Obj-C and my attempts to convert the code to Swift have not been successful.

Community
  • 1
  • 1
janson
  • 683
  • 1
  • 5
  • 14

2 Answers2

2

This is the simplest way:

let searchTextField = searchBar.valueForKey("_searchField") as! UITextField
searchTextField.inputView = myOwnInputView
Murat Uygar
  • 529
  • 6
  • 10
1

Found out that the textfield is a subview of a subview of UISearchbar.

Code to get to the textfield in swift:

var fakeView: UIView = UIView(frame: CGRectMake(100, 100, 50, 50))
@IBOutlet weak var searchBar: UISearchbar!

override func viewDidLoad() {
  fakeView.backgroundColor = UIColor.redColor()
  var c = 0
  for v in (self.searchBar.subviews[0]).subviews {
    c++
    println("\(c).\(v)") //you should see two views - UISearchBarBackground and UISearcBarTextField
    if let tf = v as? UITextField {
      //do stuff to tf here.
      //in my case, what I want is:
      tf.inputView = fakeView
      break
    }
  }
}}

Result of above code is no keyboard will show up when the searchbar text field is touched, just a red rectangle.

Note - credit goes to Matt Neuburg's "Programming iOS8: Dive Deep into Views, ViewControllers, and Frameworks (ISBN: 978-1491908730). Chapter 8 to be precise.

Muhammad Nabeel Arif
  • 19,140
  • 8
  • 51
  • 70
janson
  • 683
  • 1
  • 5
  • 14
  • Works in xcode 6.3.1. Don't want to mark this as correct since it feels like I'm giving myself points. – janson Jun 02 '15 at 04:32