取消按钮在隐藏UISearchBar键盘后消失

3

我的代码中有以下几行:

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

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

当我点击搜索按钮时,键盘会消失并且取消按钮也会消失。解决方法是什么?

你的目标是什么? - childrenOurFuture
我认为你的约束条件有问题。或者我错了吗? - Tarvo Mäesepp
@childrenOurFuture 当用户开始搜索时,导航栏将被隐藏,取消按钮将显示。导航栏将始终保持隐藏状态,直到用户点击取消按钮。 - Mohammed
@TarvoMäesepp 取消按钮是内置于UISearchBar中的,无法向其添加约束。 - Mohammed
1个回答

1

问题已解决!

我通过在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()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接