【问题标题】:UITextField with PickerView: Don't allow editing带有 PickerView 的 UITextField:不允许编辑
【发布时间】:2015-11-28 22:09:42
【问题描述】:
我有一个与 PickerView 关联的 UITextField(PickerView 是 textField 的 inputView)
Il 工作正常,但我想禁止在我的 TextField 中进行编辑(无法选择、复制文本、查看插入点……)。
我在这里为 uITextField 的委托实现 textField shouldChangeCharactersInRange,但它不起作用...
该方法从未被调用,但委托已正确完成,因为如果我实现 textFieldShouldBeginEditing,它就会被调用。
有什么(简单的)方法可以做我想做的事吗?
【问题讨论】:
标签:
ios
swift
uitextfield
uipickerview
【解决方案1】:
提供您的UITextField id,然后实现textFieldShouldBeginEditing 委托。在这些委托中,检查textField id,如果它与您想要的textField 匹配,运行函数来调用您的选择器视图并在textFieldShouldBeginEditing 委托中返回false。
【解决方案2】:
除非结果完全是选择器的结果,否则以下内容不允许粘贴和剪切文本。例如,我假设这是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
}