Swift 为什么textfield委托不能以编程方式在textfield上设置文本?
我在textfield中以编程方式设置文本,文本是生日,但代理不起作用,如果我使用本机键盘,则代理起作用,但如果我在textfield上以编程方式设置文本,则代理不起作用 我用的是swift 4.2Swift 为什么textfield委托不能以编程方式在textfield上设置文本?,swift,delegates,textfield,xib,Swift,Delegates,Textfield,Xib,我在textfield中以编程方式设置文本,文本是生日,但代理不起作用,如果我使用本机键盘,则代理起作用,但如果我在textfield上以编程方式设置文本,则代理不起作用 我用的是swift 4.2 import UIKit class userBirthdateViewController: UIViewController, UITextFieldDelegate, NumberCalculable { @IBOutlet weak var messageBirthdate: U
import UIKit
class userBirthdateViewController: UIViewController, UITextFieldDelegate, NumberCalculable {
@IBOutlet weak var messageBirthdate: UILabel!
@IBOutlet weak var inputBirthdate: UITextField!
@IBOutlet weak var keyboardView: keyboardView!
override func viewDidLoad() {
super.viewDidLoad()
messageBirthdate.text = "Debes tener 18 años cumplidos para\npoder abrir una cuenta Flink"
inputBirthdate.attributedPlaceholder = NSAttributedString(string: "DD-MM-AAAA", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
self.inputBirthdate.inputView = UIView()
self.inputBirthdate.becomeFirstResponder()
keyboardView.delegate = self
inputBirthdate.delegate = self
// Do any additional setup after loading the view.
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == inputBirthdate {
// check the chars length dd -->2 at the same time calculate the dd-MM --> 5
if (inputBirthdate?.text?.count == 2) || (inputBirthdate?.text?.count == 5) {
//Handle backspace being pressed
if !(string == "") {
// append the text
inputBirthdate?.text = (inputBirthdate?.text)! + "-"
}
}
// check the condition not exceed 9 chars
return !(textField.text!.count > 9 && (string.count ) > range.length)
}
else {
return true
}
}
@IBAction func probe(_ sender: Any) {
}
func addNumber(_ number: Int) {
if number != -1
{
inputBirthdate.insertText("\(number)")
}
else
{
if !inputBirthdate.text!.isEmpty
{
inputBirthdate.text?.removeLast()
}
}
}
}
我希望textfield的响应类似于本机键盘,唯一的区别是我以编程方式设置textfield上的文本
我使用self.inputBirthdate.inputView=UIView()行,因为我不希望本机键盘出现,而只希望光标出现
我如何解决这个问题
我尝试使用set-insertText,但不起作用:(委托方法仅响应用户输入。设置文本后,您需要手动调用委托方法
正如我在你的问题中所看到的,你不想显示默认键盘来输入出生日期。我建议你使用UIDatePicker来代替键盘,这样你就不需要自己进行验证。此外,你还可以在UIDatePic的帮助下指定最小和最大年龄限制是的,但是我的“老板”想要一个自定义键盘,我知道日期选择器会做得很简单,但这就是生活。(@AndresGomez)然后手动调用代理。当你从自定义键盘获得事件时,再调用这些代理方法