How can I set an accessibility trait for the placeholder text in UITextField?

一笑奈何 提交于 2019-12-01 17:17:43
Andrew Tetlaw

I believe you can set the accessibilityLabel and other accessibility properties on an NSString object and then use that string as your placeholder text. Voiceover will discover that property and use it.

NSString *placeholderText = @"Search";
placeholderText.accessibilityLabel = @"Try searching for xxxx";
field.placeholder = placeholderText;

Something like that. Untested, but I saw it in one of the WWDC developer videos.

WARNING: The behavior in iOS 8.0 and up is not as expected.

//In iOS 8+
NSString *placeholderText = @"Search"; //This will be announced
placeholderText.accessibilityLabel = @"Try searching for xxxx";//This will be ignored
field.placeholder = placeholderText;

This answer should be considered outdated.

Derive a custom class from UITextField as follows (code is in Swift but you can adapt to Objective-C):

class MyTextField: UITextField {
    override public var accessibilityValue: String? {
        get { return self.text }
        set { super.accessibilityValue = newValue }
    }
}

Use this class as a custom class instead of UITextField. This will stop VoiceOver from reading the placeholder text when the field is empty.

Then set your accessibility label to e.g. "Search" and accessibility hint to whatever you want to hint (see Apple's Guidelines for Creating Hints). You can assign those values programmatically, though it's probably best to assign them in Interface Builder.

You can't. Traits only make sense on Accessibility Elements. For your UITextField to be "static text" is probably not correct. Setting the trait on the item within the text field will have no effect, even though it may be valid code.

What you can do, is edit the accessibilityLabel of the control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!