Search code examples
swiftuitextfieldautocorrect

How can I disable auto-correct on an input box?


I'd like to disable auto-correct on an input box in my app. I've found a solution for objective-c that looks like this:

    UITextField* f = [[UITextField alloc] init];
    f.autocorrectionType = UITextAutocorrectionTypeNo;

I've tried implementing it like this, but it doesn't work:

    // in my viewController
    @IBOutlet weak var webAddressInput: UITextField!
    // in my viewDidLoad
    webAddressInput.autocorrectionType = UITextAutocorrectionTypeNo

How can I disable auto-correct on an input box in Swift?


Solution

  • Swift's treatment of enums takes a little getting used to. If you search on UITextAutocorrectionTypeNo in the docs, it leads you to the umbrella type UITextAutocorrectionType.

    The Swift definition of that type is

    enum UITextAutocorrectionType : Int {
        case Default
        case No
        case Yes
    }
    

    In Swift you use type.value, so this would be

    UITextAutocorrectionType.No
    

    Your line would be

    webAddressInput.autocorrectionType = UITextAutocorrectionType.No
    

    (Although, looking at the docs, I don't see an autocorrectionType property on UITextField)