【问题标题】:Entering Date in dd-MM-yyyy format using numeric keyboard in UITextField swift 3.0在 UITextField swift 3.0 中使用数字键盘以 dd-MM-yyyy 格式输入日期
【发布时间】:2017-02-13 09:43:05
【问题描述】:

我想在输入 UITextField 时格式化(dd-MM-yyyy)文本,我使用的是 swift 3.0,任何建议我该如何实现。

【问题讨论】:

  • 我会建议,创建一个日期选择器,它以您想要的格式显示日期,并将该选择器视图作为该文本字段的输入视图。
  • 到现在都没试过,不知道怎么实现
  • 设计要求是用键盘而不是选择器来实现,日期选择器已经在工作
  • 投反对票的请发表评论。

标签: ios objective-c iphone swift swift3


【解决方案1】:

像这样使用

// 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

}

//在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
    }
}

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;

}

【讨论】:

  • 感谢 Anbu.Karthik,它按要求工作,如果您能提供帮助,请提出一个小问题。我只想要数字字符,数字键盘也有小数点。我怎样才能避免这种情况?
【解决方案2】:

为 Swift 5 更新

if textField == dateTextField {
            if dateTextField.text?.count == 2 || dateTextField.text?.count == 5 {
                //Handle backspace being pressed
                if !(string == "") {
                    // append the text
                    dateTextField.text = dateTextField.text! + "."
                }
            }
            // check the condition not exceed 9 chars
            return !(textField.text!.count > 9 && (string.count ) > range.length)
        } else {
            return true
        }

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多