我想使用 UITextField 的实例变量并为每个 UITextField 实例设置不同的过滤器。我该怎么做?
class ViewController: UITextFieldDelegate {
...
func ... {
...
textField1.delegate = self
textField2.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// but the problem that textField1, textField2 should be class variables, not instance variables...
if textField1 == textField {
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
return string == numberFiltered
} else if textField2 == textField { ... }
...
}
更新
在 Android 中我可以做这样的事情
editText1.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// if...
return ...
};
});
editText2.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// if...
return ...
};
});
editText1
和 editText2
都是实例变量
最佳答案
您可以通过创建单独的 UITextFieldDelegate 子类并将它们分配为委托(delegate)来执行类似的操作。
基本方法:
class AlphaOnlyTextFieldDelegate: NSObject, UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("Alpha:", string)
// do what you want - such as allowing only Alpha chars
return true
}
}
class NumbersOnlyTextFieldDelegate: NSObject, UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("Numbers:", string)
// do what you want - such as allowing only Numeric chars
return true
}
}
class TheChildVC: UIViewController {
@IBOutlet var tfAlpha: UITextField!
@IBOutlet var tfNumbers: UITextField!
var alphaDelegate = AlphaOnlyTextFieldDelegate()
var numbersDelegate = NumbersOnlyTextFieldDelegate()
override func viewDidLoad() {
super.viewDidLoad()
tfAlpha.delegate = alphaDelegate
tfNumbers.delegate = numbersDelegate
}
}
编辑:
上述的一个优点是您可以将“预先设计的”委托(delegate)分配给任何文本字段。
另一种方法是子类 UITextField
,其委托(delegate)函数作为其自身的一部分:
class AlphaTextField: UITextField, UITextFieldDelegate {
override init(frame: CGRect) {
super.init(frame: frame)
self.delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("Alpha Class:", string)
// do what you want - such as allowing only Alpha chars
return true
}
}
关于ios - UITextField 的不同过滤器(实例变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48790269/