将 :00 附加到文本字段中输入的任何内容
append :00 to whatever is entered in the textfield
我下面的代码限制用户只能在文本字段中输入 2 个数字。我想要做的就是将“:00”附加到输入到文本字段中的任何内容。因此,如果用户输入 30。文本字段应为 30:00。下面列出了所有代码。
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var txtMobileNumber: UITextField!
let MAX_LENGTH_PHONENUMBER = 2
let ACCEPTABLE_NUMBERS = "0123456789"
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength: Int = textField.text!.count + string.count - range.length
let numberOnly = NSCharacterSet.init(charactersIn: ACCEPTABLE_NUMBERS).inverted
let strValid = string.rangeOfCharacter(from: numberOnly) == nil
return (strValid && (newLength <= MAX_LENGTH_PHONENUMBER))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
txtMobileNumber.delegate = self
}
}
你需要
aTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
if textField.text!.count == 2 {
textField.text = textField.text! + ":00"
}
}
我下面的代码限制用户只能在文本字段中输入 2 个数字。我想要做的就是将“:00”附加到输入到文本字段中的任何内容。因此,如果用户输入 30。文本字段应为 30:00。下面列出了所有代码。
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var txtMobileNumber: UITextField!
let MAX_LENGTH_PHONENUMBER = 2
let ACCEPTABLE_NUMBERS = "0123456789"
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength: Int = textField.text!.count + string.count - range.length
let numberOnly = NSCharacterSet.init(charactersIn: ACCEPTABLE_NUMBERS).inverted
let strValid = string.rangeOfCharacter(from: numberOnly) == nil
return (strValid && (newLength <= MAX_LENGTH_PHONENUMBER))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
txtMobileNumber.delegate = self
}
}
你需要
aTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
if textField.text!.count == 2 {
textField.text = textField.text! + ":00"
}
}