ios - 解除 UISearchBar 键盘后取消按钮消失

标签 ios swift uisearchbar cancel-button

我的代码中有以下几行:

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

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
}

当我点击搜索按钮时,键盘消失,取消按钮消失。

解决方案是什么?

最佳答案

已解决!

我通过在 UISearchBar 旁边添加 UIButton [cancelButton] 解决了这个问题,并将宽度约束添加为 @IBOutlet。现在,我不再显示 searchBar 的 cancelButton,而是更改 cancelButton 的宽度以显示或隐藏,如下所示:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    UIView.animateWithDuration(0.25) {
        self.widthConstraint.constant = 44.0
        self.cancelButton.layoutIfNeeded()
    }
}

@IBAction func cancelButtonTapped(sender: UIButton) {
    UIView.animateWithDuration(0.25) {
        self.widthConstraint.constant = 0.0
        self.cancelButton.layoutIfNeeded()
    }
}

关于ios - 解除 UISearchBar 键盘后取消按钮消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38193471/

相关文章:

ios - 调用 addChildViewController 或不调用 addChildViewController

objective-c - 使用 sqlite 在 Xcode 中进行空检测

ios - 使用参数执行存储在 NSMutableArray 中的 block

ios - 无法在 Xcode 6.1/段错误 : 11 中存档工作 6.0.1 Swift 项目

swift - 什么是 iOS < 9 的 CNLabeledValue 替代品?

ios - 一对多关系核心数据只保存最后一个对象。别人不见了

ios - 默认隐藏 UITableView 搜索栏

ios - XCode 立即崩溃(Swift 2.2)

iOS JSON 搜索阻塞 UI

ipad - UIToolbar 中的 UISearchBar 不会显示取消按钮