我已经创建了一个自定义输入视图,用于将文本输入到UITextField中。基本上它只是一个定制的数字键盘。我有文本字段,我在其上设置了inputView属性以使用我自定义创建的UIView子类。在视图中,我有一系列按钮--从0到9,还有退格键。
现在,我想在点击这些按钮时以编程方式更改UITextField的文本。UITextField采用UITextInput协议,而UIKeyInput协议又采用The协议。在该协议中,我有我需要的所有方法,即在光标位置插入文本和删除文本。
问题是这些方法不会触发UITextField委托方法。例如,如果我在textField:shouldChangeCharactersInRange:replacementString:字段中有自定义验证,它将不起作用。我尝试过直接设置UITextField的text属性,但同样不起作用。
在UITextField中插入文本的正确方式是什么,我的意思是以一种所有委托方法都会被调用的方式插入文本?
发布于 2016-10-26 00:56:14
通过调用insertText设置UITextField的文本:
aTextField.insertText(" ")发布于 2016-09-13 04:03:56
我试过使用textField:shouldChangeCharactersInRange:replacementString:,但没走运。当我尝试调用该方法时,我一直遇到“发送到实例的错误选择器”崩溃。
我也尝试引发了Editing事件,但是我仍然没有到达我的UITextFieldDelegate的ShouldChangeText重写中的断点。
我决定创建一个helper方法,它要么调用文本字段的委托(如果存在),要么调用虚拟ShouldChangeCharacters方法;然后根据返回的true或false更改文本。
我使用的是Xamarin.iOS,所以我的项目是用C#编写的,但是下面的逻辑可以很容易地用Objective-C或Swift重写。
可以像这样调用:
var replacementText = MyTextField.Text + " some more text";
MyTextField.ValidateAndSetTextProgramatically(replacementText);Extension Helper类:
/// <summary>
/// A place for UITextField Extensions and helper methods.
/// </summary>
public static class UITextFieldExtensions
{
/// <summary>
/// Sets the text programatically but still validates
/// When setting the text property of a text field programatically (in code), it bypasses all of the Editing events.
/// Set the text with this to use the built-in validation.
/// </summary>
/// <param name="textField">The textField you are Setting/Validating</param>
/// <param name="replacementText">The replacement text you are attempting to input. If your current Text is "Cat" and you entered "s", your replacement text should be "Cats"</param>
/// <returns></returns>
public static bool ValidateAndSetTextProgramatically(this UITextField textField, string replacementText)
{
// check for existing delegate first. Delegate should override UITextField virtuals
// if delegate is not found, safe to use UITextField virtual
var shouldChangeText = textField.Delegate?.ShouldChangeCharacters(textField, new NSRange(0, textField.Text.Length), replacementText)
?? textField.ShouldChangeCharacters(textField, new NSRange(0, textField.Text.Length), replacementText);
if (!shouldChangeText)
return false;
//safe to update if we've reached this far
textField.Text = replacementText;
return true;
}
}发布于 2016-01-19 18:40:33
self.textfield.delegate = self;
[self.textfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];当委托方法在另一个类中时,/*将自己的视图控制器对象放入另一个类中*/
在文本视图发生更改时调用/* textfield delagete */
-(void)textFieldDidChange:(UITextField *)textView
{
if(Condition You want to put)
{
//Code
}
else
{
//Code
}
}在解析此方法时,您还希望创建自定义方法。
https://stackoverflow.com/questions/24753742
复制相似问题