searchBarController在搜索时不跟随文本,取消不会像

时间:2016-02-03 15:36:56

标签: swift uisearchbar

我按照this教程创建了一个自定义搜索栏但是我遇到了几个问题。当我在搜索栏中键入文本并且我将超过文本框的内容时,文本就会消失,它不会像指示的那样跟随指针。

我遇到的第二个问题是取消按钮不能正常工作,我必须在我的CustomSearchController类中跟随一段代码

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    customSearchBar.resignFirstResponder()
    customDelegate.didTapOnCancelButton()
}

但点击取消按钮时,文字仍保留在搜索栏中

有谁知道我哪里出错或者我能做些什么来解决这些问题。

编辑:好吧,第一个问题似乎是搜索文本框的字体大小。我把它设置为20但是任何高于18的东西都会停止跟随文本。我怎么能解决这个问题。下面的代码显示了我如何设置customSearchController

customSearchController = CustomSearchController(searchResultsController: self, searchBarFrame: CGRectMake(0.0, 0.0, tblSearchResults.frame.size.width, 100.0), searchBarFont: UIFont(name: "Futura", size: 20)!, searchBarTextColor: UIColor.greenColor(), searchBarTintColor: UIColor.blackColor())

1 个答案:

答案 0 :(得分:0)

尝试如下操作。你应该知道它是如何工作的。我假设您的UI控制器是表1:

public class YourController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating {


private var searchController: UISearchController?   // your search controller


override public func viewDidLoad() {
    super.viewDidLoad()


    // create search controller

    self.searchController = UISearchController(searchResultsController: nil)
    self.searchController!.searchResultsUpdater = self
    self.searchController!.dimsBackgroundDuringPresentation = false
    self.searchController!.hidesNavigationBarDuringPresentation = false
    self.searchController!.searchBar.delegate = self
    self.searchController!.searchBar.returnKeyType = .Done
    self.searchController!.searchBar.enablesReturnKeyAutomatically = true
    self.searchController!.searchBar.sizeToFit()
    self.searchController!.searchBar.searchBarStyle = .Minimal
    self.tableView.tableHeaderView = self.searchController!.searchBar    // add search bar to table header

}


public func updateSearchResultsForSearchController(searchController: UISearchController) {
    // called after the user enters some text into the search bar
    if let searchString = searchController.searchBar.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) where !searchString.isEmpty {

       // you should filter the table array here and load your table with those data
    }
    self.tableView.reloadData() // reload your table
}


public func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    // some action after user clicks on the return button if needed 
}

public func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    // search canceled -> you should add all the objects back here to the Table Array
}


public func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
    self.updateSearchResultsForSearchController(self.searchController!)
}

}

或者你可以通过观察这个来获得一些想法: Some Github example