【发布时间】:2019-06-25 17:52:12
【问题描述】:
我在文本字段中以编程方式设置文本,文本是生日,但委托不起作用,如果我使用本机键盘,委托工作,但如果我在文本字段上以编程方式设置文本,委托不起作用
我正在使用 swift 4.2
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()
}
}
}
}
我希望文本字段像本机键盘一样响应,唯一的区别是我以编程方式设置文本字段上的文本。
我使用这一行 self.inputBirthdate.inputView = UIView() 因为我不希望出现本机键盘,而只显示光标
我该如何解决这个问题?
我尝试使用 set insertText 但不起作用:(
【问题讨论】:
标签: swift delegates textfield xib