Search code examples
swiftkeyboarduitextfield

extension for UITextfield keyboard appearance


in my app, I will add different themes, but for now, I want to write an extension that can handle keyboard appearance from extension. for the first step, I just want to have control of its appearance, so I set that it should be .dark but it's not working. could you tell me where is the problem in this simple extension? I just want it to change the keyboard appearance automatically without doing anything else

extension UITextView {


  var keyboardApperance: UIKeyboardAppearance? {
    get {
        return self.keyboardAppearance
    }
    set {
         self.keyboardAppearance = .dark
    }
  }
}

Solution

  • Creating just an extension doesn't change your UITextView properties.

    You can create your own custom UITextView and use it instead of UITextView.

    Don't forget to set your class if you are using storyboard or xib.

    @IBDesignable
    public class CustomDarkTextView: UITextView {
    
        public override init(frame: CGRect, textContainer: NSTextContainer?) {
            super.init(frame: frame, textContainer: textContainer)
            setup()
        }
    
        public convenience init(frame: CGRect) {
            self.init(frame: frame, textContainer: nil)
            setup()
        }
    
        public convenience init() {
            self.init(frame: CGRect.zero, textContainer: nil)
            setup()
        }
    
        public required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            self.keyboardAppearance = UIKeyboardAppearance.Dark
        }
    }