skip to Main Content

I want all of TextField to have small letters.and if I need to change to a larger one I could write inside the creation.But my code doesn’t work, what am I doing wrong?

class ViewController: UIViewController

 private let TextField: CustomTextField = { //LETTERS (no work)
        let textfield = CustomTextField() 
        textfield.autocapitalizationType = .allCharacters 
        return textfield
    }()
private let TextField2: CustomTextField = { //letters (work)
    let textfield = CustomTextField() 
    return textfield
}()


  

class CustomTextField: UITextField

override func layoutSubviews() {
    super.layoutSubviews() 
    self.autocapitalizationType = .none 
}

2

Answers


  1. layoutSubviews() function is called after the initialization of your textFields. If you debug your code, you will see that TextField.autocapitalizationType will be set to .allCharacters. But after initialization of your object, layoutSubviews() will be called and autocapitalizationType will be set to .none. So you need to define the self.autocapitalizationType = .none inside init of your CustomTextField.

    Login or Signup to reply.
  2. First, remove the override of layoutSubviews() – as mentioned by Muhammed’s answer, setting the autocapitalizationType here will overwrite your custom value as soon as layoutSubviews() is called.

    Then, if you give your CustomTextField a custom initializer with a parameter for the capitalization type like this:

    init(autocapitalizationType: UITextAutocapitalizationType = .none) {
        super.init(frame: .zero)
        self.autocapitalizationType = autocapitalizationType
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    Then you can just initialize it all in one step like this, no closure required:

    private let textField = CustomTextField(autocapitalizationType: .allCharacters)
    

    If you don’t want to set a type then you can leave the CustomTextField() parentheses empty since the initializer adds .none as a default.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search