UITextField with PickerView:不允许编辑



我有一个与PickerView关联的UITextField(PickerView是textField的inputView)Il工作正常,但我想禁止在我的TextField中进行编辑(不能选择、复制文本、查看插入点…)。我在这里为uITextField的委托实现textField shouldChangeCharactersInRange,但它不起作用。。。该方法从未被调用,但委托是正确完成的,因为如果我实现textFieldShouldBeginEditing,它就会被调用。有什么(简单的)方法可以做我想做的事吗?

给出您的UITextField id,然后实现textFieldShouldBeginEditing委托。在这些委托中,检查textField id,如果它与您想要的textField匹配,则运行函数调用您的picker视图,并在textFieldShouldBeginEditing委托中返回false。

以下内容禁止粘贴和剪切文本,除非结果与选择器的结果完全相同。例如,我假设这是一个UIDatePicker

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    return string == formatter.stringFromDate(datePickerView.date)
}

其中格式化程序类似于

    let formatter = NSDateFormatter()
    formatter.locale = NSLocale.currentLocale()
    formatter.dateFormat = "dd/MM/yyyy"

此外,如果您以编程方式将文本字段设置为字符串日期,则可能需要将文本字段的inputView选择器与同步

func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
    if let text = textField.text {
        if let date = formatter.dateFromString(text) {
            datePickerView.setDate(date, animated: true)
        }
    }
    return true
}

最新更新