swift 有没有办法在编辑时只激活搜索栏上的取消按钮?

beq87vna  于 2023-01-04  发布在  Swift
关注(0)|答案(2)|浏览(147)

我知道您可以使用文本字段上的清除按钮来执行此操作,如下所示:

searchController?.searchBar.searchTextField.clearButtonMode = .whileEditing

但是搜索栏上的取消按钮有类似的功能吗?

searchController?.searchBar.showsCancelButton = true // this exists
searchController?.searchBar.cancelButtonMode = .whileEditing // I could not find this

谢谢大家!

z4bn682m

z4bn682m1#

如果您不希望在用户实际点击搜索控制器的搜索栏之前显示搜索栏,请不要为“取消”按钮添加任何代码。默认行为是在用户激活搜索之前不显示“取消”按钮。
只需删除任何代码,你必须设置或更改取消按钮。
从iOS 13开始,你可以使用UISearchControllerautomaticallyShowsCancelButton属性,但在iOS中默认为true。在Mac Catalyst下似乎默认为false

dbf7pr2w

dbf7pr2w2#

不,没有你提到的直接方法,但是你可以通过它的委托方法来做。

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(true, animated: true)
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
}

这些是搜索文本域编辑和结束编辑时的方法。这将完全满足您的目的。

相关问题