我对文本字段有疑问。
如果我想要文本字段仅允许使用字符和数字。
我不希望用户输入../?...ect
我在堆栈中搜索,没有找到它。
该怎么做?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textfield: UITextField!
//textField keyboard type is UIKeyboardTypeASCIICapable
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
}
@IBAction func buttonClicked(_ sender: Any) {
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !string.containsValidCharacter
}
}
extension String {
var containsValidCharacter: Bool {
let characterSet = CharacterSet(charactersIn: "")
let range = (self as NSString).rangeOfCharacter(from: characterSet)
return range.location != NSNotFound
}
}