为什么我的UIView不会显示UISearchBar

时间:2016-07-28 17:28:36

标签: ios uitableview uiview uikit uisearchbar

我想在我的故事板中设置一个等于我UISearchBar的{​​{1}}的UIView由于某种原因这段代码:

UISearchController

不会显示搜索栏。但是这个:

@IBOutlet weak var theView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    let searchController = UISearchController(searchResultsController: nil)
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.sizeToFit()
    theView = searchController.searchBar

}

意愿。为什么? @IBOutlet weak var tblSearchResults: UITableView! override func viewDidLoad() { super.viewDidLoad() let searchController = UISearchController(searchResultsController: nil) searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search here..." searchController.searchBar.sizeToFit() tblSearchResults.tableHeaderView = searchController.searchBar } 标题视图是UITableView,为什么它的行为不同?

1 个答案:

答案 0 :(得分:0)

不打算就这么做的原因提出任何建议,但为了帮助解决您的具体问题......

检查...分配后,searchController.searchBar引用将复制到theView。 searchBar没有superview,因此theView也没有。然后,您可以将searchController.searchBartheView添加回子视图,因为它们都具有相同的参考。

@IBOutlet weak var theView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    let searchController = UISearchController(searchResultsController: nil)
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.sizeToFit()
    print("theView0 \(theView.superview)")

    theView = searchController.searchBar
    print("theView1 \(theView.superview)") //notice this is nil now

    view.addSubview(theView) //OR view.addSubview(searchController.searchBar)

    print("theView2 \(theView.superview)")
}