Home:ALL Converter>Where to set UiTextField delegate method in custom UiView

Where to set UiTextField delegate method in custom UiView

Ask Time:2016-09-21T21:23:18         Author:Gaurav

Json Formatter

Error occurs when I set UITextField delegate.

My code is:

import UIKit

class UserAlertVC: UIView , UITextFieldDelegate {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code
}
*/

override init(frame: CGRect) {
    super.init(frame: frame)

}

required init(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)!
    self.addBehavior()

}


func addBehavior (){
    print("Add all the behavior here")
    userNameTxtField.delegate = self
    passwordTxtField.delegate = self

}


func textFieldShouldReturn(textField: UITextField) -> Bool {

    return true
}

func textFieldDidBeginEditing(textField: UITextField) {

}


@available(tvOS 10.0, *)
func textFieldDidEndEditing(textField: UITextField, reason: UITextFieldDidEndEditingReason) {

}

@IBAction func actionOnCancel(sender: UIButton) {
    self .removeFromSuperview()


}


@IBAction func actionOnProceed(sender: UIButton) {
    self .removeFromSuperview()
UserAlertVC.showAlertForUser()


}

@IBOutlet var userNameTxtField: UITextField!

@IBOutlet var passwordTxtField: UITextField!

static func showAlertForUser() {

    let alert       = NSBundle.mainBundle().loadNibNamed("KeyboardViewController", owner: self, options: nil)!.last as! UIView
    let windows     = UIApplication.sharedApplication().windows
    let lastWindow  = windows.last
    alert.frame     = UIScreen.mainScreen().bounds
    lastWindow?.addSubview(alert)


}
}

Error message is:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have used Custom Alert View using XIB.pls suggest any solution.

Author:Gaurav,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39617849/where-to-set-uitextfield-delegate-method-in-custom-uiview
Oleg Gordiichuk :

Firstly take a look at life cycle of the view. Depending on this it is possible to highlight that method awakeFromNib is quite suitable because:\n\n\n The nib-loading infrastructure sends an awakeFromNib message to each\n object recreated from a nib archive, but only after all the objects in\n the archive have been loaded and initialized. When an object receives\n an awakeFromNib message, it is guaranteed to have all its outlet and\n action connections already established.\n",
2016-09-21T13:32:41
yy