设置Searchbar的输入视图 - Swift

时间:2015-06-01 04:15:19

标签: swift uisearchbar

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
  }

}

我正在尝试将自定义输入视图分配给我的搜索栏,但是基于Apple文档(-sorry找不到链接),对于UISearchBar,它似乎是一个只读值。查看this post,看起来UISearchbar有多个子视图,我需要访问UITextField部分才能更改输入视图。但是,我对Obj-C并不熟悉,我将代码转换为Swift的尝试并没有成功。

2 个答案:

答案 0 :(得分:1)

发现textfieldUISearchbar子视图的子视图。

使用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
    }
  }
}}

以上代码的结果是当触摸搜索栏文本字段时,没有键盘会显示,只是一个红色矩形。

注意 - 功劳归功于Matt Neuburg的“编程iOS8:潜入视图,ViewControllers和框架(ISBN:978-1491908730)。准确地说,第8章。

答案 1 :(得分:1)

这是最简单的方法:

let searchTextField = searchBar.valueForKey("_searchField") as! UITextField
searchTextField.inputView = myOwnInputView