iosswiftuisearchbaruiaccessibility

UISearchBar access to clear text button for UIAccessibility


For a personal application conform to UIAccessibility and VoiceOver I need to change the UIAccessibilty label of the clear text button (gray cross) in a UISearchBar.

I don't now how to access to this element.

I try something like

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

  weak var btnCancel: UIButton?

  override func viewDidLoad()
  {
    super.viewDidLoad()

    for subView in searchBar.subviews
    {
      for subSubView in subView.subviews
      {
        if subSubView.isKindOfClass(UIButton)
        {
          btnCancel = subSubView as? UIButton

          btnCancel?.isAccessibilityElement = true

          btnCancel?.accessibilityLabel =  NSLocalizedString("Clear Text", comment: "")
        }
      }
    }
  }
}

I try it on viewDidLoad ; searchBar textDidChange ; searchBarTextDidBeginEditing ;

I never found any button

Your help is welcome


Solution

  • Thanks to Joanna Carter from french website Cocoacafe.fr

    Solution :

    @IBOutlet weak var searchBar: UISearchBar!
    
      override func viewDidLoad()
      {
        super.viewDidLoad()
    
        for subView in searchBar.subviews
        {
          for sView in subView.subviews
          {
            if let textField = sView as? UITextField,
               let clearButton = textField.valueForKey("clearButton") as? UIButton
            {
              clearButton.isAccessibilityElement = true
    
              clearButton.accessibilityLabel =  NSLocalizedString("Clear Text", comment: "")
            }
          }
        }
      }