gpt4 book ai didi

swift - 如何在 Swift 的单独类中设置 UITextField 的委托(delegate)?

转载 作者:可可西里 更新时间:2023-11-01 01:20:43 26 4
gpt4 key购买 nike

我试图在单独的类中实现 UITextFieldDelegate,但它没有工作:

class ViewController: UIViewController {

@IBOutlet var TextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
let restrictor = TextFieldRestrictController()
TextField.delegate = restrictor
}
}

class TextFieldRestrictController : NSObject, UITextFieldDelegate {

public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let inverseSet = NSCharacterSet(
charactersIn:"0123456789.").inverted

let components = string.components(separatedBy: inverseSet)

let filtered = components.joined(separator:"")
return string == filtered
}
}

但这是可行的:

class ViewController: UIViewController {

@IBOutlet var TextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
TextField.delegate = self
}

public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let inverseSet = NSCharacterSet(
charactersIn:"0123456789.").inverted

let components = string.components(separatedBy: inverseSet)

let filtered = components.joined(separator:"")
return string == filtered
}
}

有什么问题吗?

最佳答案

UITextField.delegate是一个 weak 属性,所以在 viewDidLoad 方法的末尾,restrictor 将被释放,因为周围没有其他强引用指向它所指向的对象。

您可以尝试在 viewDidAppear(animated:) 中打印出 ValidationTextField.delegate 并查看它返回 nil

为了解决这个问题,您可以将 restrictor 定义为实例变量,这样只要 View Controller 处于事件状态,它就会保持事件状态:

class ViewController: UIViewController {
@IBOutlet weak var ValidationTextField: UITextField!

let restrictor = TextFieldRestrictController()

override func viewDidLoad() {
super.viewDidLoad()
ValidationTextField.delegate = restrictor
}
}

关于swift - 如何在 Swift 的单独类中设置 UITextField 的委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020105/

26 4 0
文章推荐: java - 缺少 Artifact org.springframework :spring-context:jar:${org. springframework-version}
文章推荐: javascript - 类型 'Observable' 不可分配给类型 'Observable'