当 UIView 接收到accessibilityElementDidLoseFocus 时如何关闭键盘

问题描述 投票:0回答:2

我有一个搜索视图控制器,搜索栏位于顶部。搜索时,即使在搜索栏上调用

accessibilityElementDidLoseFocus
,键盘也会显示并保持不动。

发生这种情况时我想关闭键盘。我可以在不子类化我正在使用的搜索栏的情况下做到这一点吗?

swift accessibility uiaccessibility
2个回答
0
投票

这是一种无需子类化即可实现此目的的方法:

// Assuming you have an accessibility element with an identifier
let myAccessibilityElement = UIAccessibilityElement(accessibilityContainer: self)

// Observe accessibility focus changes
NotificationCenter.default.addObserver(
    self, 
    selector: #selector(accessibilityElementDidLoseFocus), 
    name: UIAccessibilityElement.didLoseFocusNotification, 
    object: myAccessibilityElement
)

@objc func accessibilityElementDidLoseFocus() {
    // Dismiss keyboard here
}

-1
投票

要在 UIView 失去焦点时关闭键盘而不对搜索栏进行子类化,您可以实现 UISearchBarDelegate (或 UITextFieldDelegate)并使用 searchBarCancelButtonClicked (或文本字段的类似方法)在活动搜索栏或文本上调用 resignFirstResponder()领域。

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.delegate = self
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.