Search code examples
swiftcosmicmind

Material Textfield crash on setting error text


I am using the CosmicMind library for Material design and I am trying to set up basic textfields with some error checking but the documentation is not very good.

I have set up my text fields like the following:

@IBOutlet weak var userNameField: ErrorTextField!

userNameField.placeholder = "Enter Username"
userNameField.delegate = self
userNameField.error = "Text is too long" // App Crashes here
userNameField.errorColor = Color.red.base

App crashes with EXC_BAD_ACCESS

I validate my field like this:

func textField(textField: TextField, didChange text: String?) {

    if textField == userNameField {

        if validateUsername(text: textField.text!) {
            userNameField.isErrorRevealed = true
        } else {
            userNameField.isErrorRevealed = false
        }
    }
}

Even if I remove that line, app crashes on userNameField.isErrorRevealed = true too.


Solution

  • I have created following code with same library which are you using, which are working fine. I have create textField programatically.

    import UIKit
    import Material
    
    class ViewController: UIViewController {
    
        fileprivate var emailField: ErrorTextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = Color.grey.lighten5
    
            emailField = ErrorTextField()
            emailField.placeholder = "Email"
            emailField.error = "Text is too long"
            emailField.delegate = self
    
            self.view.layout(emailField).height(40).width(200).centerVertically().centerHorizontally()
        }
    }
    
    extension ViewController: TextFieldDelegate {
    
        public func textFieldDidEndEditing(_ textField: UITextField) {
            (textField as? ErrorTextField)?.isErrorRevealed = false
        }
    
        public func textFieldShouldClear(_ textField: UITextField) -> Bool {
            (textField as? ErrorTextField)?.isErrorRevealed = false
            return true
        }
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            (textField as? ErrorTextField)?.isErrorRevealed = true
            return true
        }
    }
    

    See this sample project: Sample Project

    I hope this will help you.