Search code examples
iosswiftaccessibilityuitextview

iOS: Not able to change the accessibility frame for my UITextView


I'm trying to change the accessibility frame for my UITextView to something smaller, but I'm not able to. This is the code that I am using.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
                
    let textView = UITextView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
    textView.isAccessibilityElement = true
    view.addSubview(textView)
                
    let rect = CGRect(x: 100, y: 100, width: 40, height: 40)
    textView.accessibilityFrame = rect
  }

Changing the accessibility frame works for UIButton or UIStackView, but not UITextView for some reason. Any insight will be deeply appreciated. Please let me know if you need anymore details.

Edit: I've also tried disabling some properties, but I'm still unsuccessful. Please see below.

textView.isEditable = false
textView.isSelectable = false
textView.isScrollEnabled = false

Solution

  • I'm trying to change the accessibility frame for my UITextView to something smaller, but I'm not able to.

    I noticed that either and at no time did I provide any accurate explanation for this behavior unfortunately. However, I found out a solution by using a UIAccessibilityElement for refining a UITextView accessibility frame.

    override func viewDidAppear(_ animated: Bool) {
            
            super.viewDidAppear(animated)
            
            let textView = UITextView(frame: CGRect(x: 100,
                                                    y: 100,
                                                    width: 100,
                                                    height: 100))
            view.addSubview(textView)
            
            let a11yElt = UIAccessibilityElement(accessibilityContainer: textView)
            a11yElt.accessibilityFrameInContainerSpace = CGRect(x: 0.0,
                                                                y: 0.0,
                                                                width: 40.0,
                                                                height: 40.0)
            a11yElt.accessibilityTraits = .staticText
            a11yElt.accessibilityLabel = "hello"
    
            textView.isAccessibilityElement = false
            textView.accessibilityElements = [a11yElt]
    }
    

    Following this rationale, you're now able to change the accessibility frame for your UITextView.