【发布时间】:2020-08-14 19:36:21
【问题描述】:
当在 swift 中使用 UITableView 和 UISearchBar 时,我试图找到一种方法来在用户搜索某些内容然后在表格视图中滚动时保持搜索栏上的取消按钮处于启用状态,这样他们就不必单击两次取消搜索。辞职第一响应者(或结束搜索栏上的编辑)的默认行为将使取消按钮变灰,但我想保持启用它,所以在 Stackoverflow 我找到了如何做到这一点,但我找不到答案在线了解searchBar.value(forKey: "cancelButton") 在下面的代码中做了什么。显然,它以某种方式在搜索栏上创建了对取消按钮的引用,但我不明白 .value 的作用(因为我是 swift 新手),以及“cancelButton”键的来源。我已经阅读了func value(forKey key: String) 文档,但我仍然不明白。如果有人能解释这是做什么的,那就太好了。
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
// If the user scrolls, keep the cancel button enabled
if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton { // <-- This line
if searchBar.text != "" { cancelButton.isEnabled = true }
else { searchBar.showsCancelButton = false }
}
}
提前致谢。
【问题讨论】:
-
stackoverflow.com/questions/4489684/… 因为
UISearchBar有一个名为cancelButton的“隐藏”属性。旁注,您正在访问一个私有变量,名称是通过逆向工程找到的。它可能会在下一个 iOS 版本中重命名,或者可能会被 AppStore 拒绝。 -
无论您是搜索还是取消搜索,您都希望取消按钮始终处于启用状态吗?对吗?
标签: swift uisearchbar