【发布时间】:2021-07-19 11:31:03
【问题描述】:
我目前在我的应用中是using UISearchController。
当点击 leftView 的搜索图标时,我想使用在 textField 中输入的文本执行一个过程(不是搜索过程)。
因此,我尝试在图标using UIGestureRecognizer and UILongPressGestureRecognizer 上添加点击手势(或长按手势),但没有任何结果。
问题 1:Does the icon originally not trigger any actions when tapped? (It doesn't even call "searchBarSearchButtonClicked" function when tapped.)
问题 2:Is there any way to use the icon like clickable button, and trigger a specific action when tapped?
下面是我的代码和屏幕图片供您参考。
如果您需要一些其他信息,请告诉我。
提前谢谢你。
更新:书签按钮未按预期工作...
我尝试了书签按钮。但是,它没有按预期工作,因为在输入文本时它隐藏在一个清晰的图标下方。
如果即使输入了文本,书签按钮也会一直显示,那将是理想的选择。
目标图标图片
属性:
let searchController = UISearchController(searchResultsController: nil)
var keyword = ""
setupSearchController:
我在下面的函数中更改了搜索图标的颜色和图像。
private func setupSearchController() {
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = true
definesPresentationContext = true
searchController.delegate = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = "Search channels"
// search icon settings
searchController.searchBar.searchTextField.leftView?.tintColor = .link
searchController.searchBar.setImage(UIImage(systemName: "globe"), for: .search, state: .normal)
}
setupTranslateButton:
我尝试了两种方法,UITapGestureRecognizer 和 UILongPressGestureRecognizer,这两种方法都没有发生任何事情。
// UITapGestureRecognizer version
private func setupTranslateButton() {
let transButton = searchController.searchBar.searchTextField.leftView!
let tap = UITapGestureRecognizer(target: self, action: #selector(translateKeyword))
transButton.addGestureRecognizer(tap)
searchController.searchBar.searchTextField.addSubview(transButton)
}
// UILongPressGestureRecognizer version
private func setupTranslateButton() {
let transButton = searchController.searchBar.searchTextField.leftView!
let tap = UILongPressGestureRecognizer(target: self, action: #selector(translateKeyword))
tap.minimumPressDuration = 0
transButton.addGestureRecognizer(tap)
}
翻译关键字:
我想要在成功触发轻击手势时调用以下函数。
@objc func translateKeyword(_ sender: UILongPressGestureRecognizer) {
print("Translate button is clicked...")
// keyword string should exist by the process executed in "updateSearchResults" function
if keyword.isEmpty {
print("Keyword is empty")
return
}
// The following process is here...
}
更新搜索结果:
每次输入 textField 时,所有文本都会放入关键字变量中。
func updateSearchResults(for searchController: UISearchController) {
print("updateSearchResults")
guard let inputKeyword = searchController.searchBar.text, !inputKeyword.isEmpty else {
print("Keyword is not entered...")
return
}
keyword = inputKeyword
}
【问题讨论】:
-
使用书签按钮怎么样?唯一的区别是它在右侧,并且没有相同的色调。
-
提示:searchBarBookmarkButtonClicked
-
感谢您的回复。我尝试了书签按钮,但在输入文本时它隐藏在一个清晰的图标下。我想在点击图标时触发的函数中输入文本。如果即使在输入文本时书签按钮仍然显示会很好......
标签: ios swift uisearchbar uisearchcontroller