如何在 UITextFieldDelegate 中进行不同的检查
How to do different checks in UITextFieldDelegate
我尝试在 UITextFieldDelegate 的函数中做一些检查,但我真的被卡住了。
在一项检查中,我想验证用户是否尝试在 UITextfield 的前面插入空格并且不允许他这样做。
在另一项检查中,我想限制用户在价格 UITextfield 中仅输入数字和标点符号。
我在那里做检查可以吗?
这是我的代码:
class AdminPanelViewController: UITableViewController {
@IBOutlet weak var productNameTextfield: UITextField!
@IBOutlet weak var productPriceTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
productPriceTextfield.delegate = self
productNameTextfield.delegate = self
}
}
extension AdminPanelViewController: UITextFieldDelegate{
// Function which allow the user to enter only digits and punctuation for Price textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
// This is for my Product Name and I want it here also
if (productNameTextfield!.text != nil){
if Int(range.location) == 0 && (string == " ") {
return false
}
else{
return true
}
}
else if (productPriceTextfield!.text != nil) {
// This is for my price and I need it here
let allowedCharacters = "0123456789."
return allowedCharacters.contains(string) || range.length == 1
}
return WHAT TO RETURN ???
}
}
感谢您的宝贵时间!!!
为价格将键盘类型更改为 numberPad
productPriceTextfield.keyboardType = UIKeyboardType.numberPad
并且 space 以这种方式使用 trim 方法:
let str = productNameTextfield!.text
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
我认为你应该检查 textField
看看你是否有正确的,像这样:
if (textfield == productNameTextfield) {
// DO STUFF
}
我尝试在 UITextFieldDelegate 的函数中做一些检查,但我真的被卡住了。 在一项检查中,我想验证用户是否尝试在 UITextfield 的前面插入空格并且不允许他这样做。 在另一项检查中,我想限制用户在价格 UITextfield 中仅输入数字和标点符号。
我在那里做检查可以吗?
这是我的代码:
class AdminPanelViewController: UITableViewController {
@IBOutlet weak var productNameTextfield: UITextField!
@IBOutlet weak var productPriceTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
productPriceTextfield.delegate = self
productNameTextfield.delegate = self
}
}
extension AdminPanelViewController: UITextFieldDelegate{
// Function which allow the user to enter only digits and punctuation for Price textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
// This is for my Product Name and I want it here also
if (productNameTextfield!.text != nil){
if Int(range.location) == 0 && (string == " ") {
return false
}
else{
return true
}
}
else if (productPriceTextfield!.text != nil) {
// This is for my price and I need it here
let allowedCharacters = "0123456789."
return allowedCharacters.contains(string) || range.length == 1
}
return WHAT TO RETURN ???
}
}
感谢您的宝贵时间!!!
为价格将键盘类型更改为 numberPad
productPriceTextfield.keyboardType = UIKeyboardType.numberPad
并且 space 以这种方式使用 trim 方法:
let str = productNameTextfield!.text
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
我认为你应该检查 textField
看看你是否有正确的,像这样:
if (textfield == productNameTextfield) {
// DO STUFF
}