Har*_*oon 0 iphone objective-c ios swift swift3
我想在进入UITextField时格式化(dd-MM-yyyy)文本,我使用swift 3.0,任何建议我如何实现相同的.
Anb*_*hik 10
用得像
// create one textfield
@IBOutlet var txtDOB: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// set delegate for your textfield
txtDOB.delegate = self
}
Run Code Online (Sandbox Code Playgroud)
//在textfield委托中调用你的函数shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Format Date of Birth dd-MM-yyyy
//initially identify your textfield
if textField == txtDOB {
// check the chars length dd -->2 at the same time calculate the dd-MM --> 5
if (txtDOB?.text?.characters.count == 2) || (txtDOB?.text?.characters.count == 5) {
//Handle backspace being pressed
if !(string == "") {
// append the text
txtDOB?.text = (txtDOB?.text)! + "-"
}
}
// check the condition not exceed 9 chars
return !(textField.text!.characters.count > 9 && (string.characters.count ) > range.length)
}
else {
return true
}
}
Run Code Online (Sandbox Code Playgroud)
的ObjectiveC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//Format Date of Birth dd-MM-yyyy
if(textField == txtDOB)
{
if ((txtDOB.text.length == 2)||(txtDOB.text.length == 5))
//Handle backspace being pressed
if (![string isEqualToString:@""])
txtDOB.text = [txtDOB.text stringByAppendingString:@"-"];
return !([textField.text length]>9 && [string length] > range.length);
}
else
return YES;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4170 次 |
| 最近记录: |