【问题标题】:Search Bar - Cancel Button in Navigation Bar搜索栏 - 导航栏中的取消按钮
【发布时间】:2015-08-15 15:01:29
【问题描述】:

我在导航栏中做搜索栏。编辑时,导航栏右侧没有取消按钮。

试过了:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

    var barButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Done, target: self, action: "")
    self.navigationItem.rightBarButtonItem = barButton
}

编辑:

我将搜索栏添加到导航栏,如下所示:

lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 300, 20))

        searchBar.placeholder = "Hľadať"
        searchBar.barStyle = UIBarStyle.BlackTranslucent
        var leftNavBarButton = UIBarButtonItem(customView:searchBar)
        self.navigationItem.leftBarButtonItem = leftNavBarButton

【问题讨论】:

  • 我很确定取消按钮是一种默认选项,因为 UISearchBar 中有一个选项明确定义了“showsCancelButton”,所以我不知道你需要放置你的那里有自己的取消按钮。
  • 我以编程方式添加了搜索栏,因为我希望它在导航栏中
  • 我明白了,那么让我为你充实另一个选择
  • @patffo 尝试将 searchBar 的 showsCancelButton 设置为 true
  • 您可以这样做,但始终会显示“取消”按钮。

标签: ios swift button searchbar


【解决方案1】:

这样做:

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    var cancelSearchBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBarButtonItemClicked")
    self.navigationItem.setRightBarButtonItem(cancelSearchBarButtonItem, animated: true)
    return true
}

在“取消”处理程序中:

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    // closes the keyboard
    searchBar.resignFirstResponder()

    // If you are using a search controller
    // self.searchDisplayControllerCustom.setActive(false, animated: true)

    // remove the cancel button
    self.navigationItem.setRightBarButtonItem(nil, animated: true)
}

func cancelBarButtonItemClicked() {
    self.searchBarCancelButtonClicked(self.searchBar)
}

并为导航栏标题文字设置正确的颜色:

// This sets the textcolor for all navigation bars in the app
// Do this in the app delegate on startup
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

并添加委托:

searchBar.delegate = self

【讨论】:

  • 请将“取消”字样放大,如“取消 AAAAAAA”,检查右边的间隙是否变大。可能只是设置了错误的颜色。
  • 我已经用颜色更新了我的答案。你是如何将搜索栏设置到导航栏中的?
  • 尝试将搜索栏设置在中心:self.navigationItem.titleView = searchBar
  • 真的叫 searchBarShouldBeginEditing 吗?你设置了代表吗?请调试。
  • 好吧,那么:searchBar.delegate = self
【解决方案2】:

如果这是 Objective-C 的答案:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES];
}

那么这可能是 Swift 的答案:(不是 100% 肯定)

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchBar.showsCancelButton = true
}

记得将你的委托与自己联系起来。

来源:UISearchBar Class Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多