gpt4 book ai didi

swift - 在自定义 UiView 中的何处设置 UiTextField 委托(delegate)方法

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:41 25 4
gpt4 key购买 nike

设置 UITextField 委托(delegate)时发生错误。

我的代码是:

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)


}
}

错误信息是:

fatal error: unexpectedly found nil while unwrapping an Optional value

我使用了使用 XIB 的自定义警报 View 。请提出任何解决方案。

最佳答案

首先看一下 View 的生命周期。根据这一点,可以强调 awakeFromNib 方法非常合适,因为:

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

关于swift - 在自定义 UiView 中的何处设置 UiTextField 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39617849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com