这段代码完美无缺,即使我尝试将其粘贴,我也无法键入整数以外的任何内容。
我想再添加一个细化,即限制输入的长度。这是我的代码:
func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
if text == "" {
return true
}
if let _ = Int(text) {
return true
}
else {
return false
}
}
我需要添加什么来实现这一目标?所有TextField的最大输入长度应为< = 4。
顺便说一下,所有代码都在Swift 2中。从我在尝试实现我之前提出的问题的答案时遇到的问题,我收集到一些方法不同。答案 0 :(得分:3)
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ...
count(textField.text)
答案 1 :(得分:1)
将textfield delegate方法中的条件写为: -
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if (count(textField.text) > 4 && range.length == 0)
{
return false // return NO to not change text
}
else
{
}
将所有代码部分写入else部分。
答案 2 :(得分:0)
委托方法或NSFormatter,如NSNumberFormatter。 格式化程序通常是最合适的,因为它还提供本地化支持。
答案 3 :(得分:0)
我知道它为时已晚,但是我仍然想分享它,我发现了一种在快速开发中为文本字段设置限制字符的方法要容易得多。
这是代码:-
import UIKit
private var maxLengths = [UITextField: Int]()
extension UITextField {
@IBInspectable var maxLength: Int {
get {
guard let length = maxLengths[self] else {
return Int.max
}
return length
}
set {
maxLengths[self] = newValue
addTarget(self, action: #selector(limitLength), for: .editingChanged)
}
}
@objc func limitLength(textField: UITextField) {
guard let prospectiveText = textField.text, prospectiveText.count > maxLength else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
#if swift(>=4.0)
text = String(prospectiveText[..<maxCharIndex])
#else
text = prospectiveText.substring(to: maxCharIndex)
#endif
selectedTextRange = selection
}
}
并通过面板设置限制。
答案 4 :(得分:0)
只需尝试限制TF的长度
编辑已更改的TF操作出口
@IBAction func otpTF2EditingChnaged(_ sender: UITextField) {
if (sender.text?.count == 1) {
otpTF3.becomeFirstResponder()
}
checkMaxLength(textField: sender , maxLength: 1)
}
将限制长度的功能
private func checkMaxLength(textField: UITextField!, maxLength: Int) {
if (textField.text!.count > maxLength) {
textField.deleteBackward()
}
}