我已按照此tutorial了解如何将textField
限制为特定长度和字符集。
这是我的代码,但代理人没有被调用:
VC类:调用它(在调试时验证)
var textManager = TextManager()
@IBOutlet weak var enterName_text: UITextField!
func onVideDidLoad() {
...
enterName_text.placeholder = StringConstans.name
enterName_text.delegate = textManager
}
TextManager类:
import Foundation
public class TextManager: NSObject, UITextFieldDelegate {
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.characters.count == 0 {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)
return prospectiveText.containsOnlyCharactersIn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") &&
prospectiveText.characters.count <= 6
}
}
答案 0 :(得分:0)
以下代码有效。你们有何不同?
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
let textManager = TextManager()
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = textManager
}
}
public class TextManager: NSObject, UITextFieldDelegate {
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print("should")
if string.characters.count == 0 {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)
return prospectiveText.containsOnlyCharactersIn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") &&
prospectiveText.characters.count <= 6
}
}
extension String {
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {
let disallowedCharacterSet = NSCharacterSet(charactersInString: matchCharacters).invertedSet
return self.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
}
}