gpt4 book ai didi

ios - 如何限制 iOS 中的前缀文本字段字符串?

转载 作者:行者123 更新时间:2023-11-29 10:30:53 26 4
gpt4 key购买 nike

如何限制textField字符串的前缀。

我想要文本字段具有默认前缀字符串(AAAA-)的效果。

(AAAA- 用户添加字符串后)

并且用户不能删除这些字符串,用户可以将字符串添加到textField

如何使用下面的委托(delegate)方法达到效果?

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

}

我不想自定义模态视图来实现这些效果。

有没有一些textfield的方法可以实现?

谢谢

--- 详细解释问题---

我使用 UIAlertAction 在 AlertAction 中添加文本字段,如下所示:

在我声明的接口(interface)处

NSString *_prefixString;

在viewdidload中设置初始值

_prefixString = @"AAAA-";

而且我在头文件中设置了 UITextFieldDelegate。

然后下面设置alertviewcontroller:

    UIAlertController *changeDeviceNameDialog =[UIAlertController
alertControllerWithTitle:NSLocalizedString(@"change_device_name",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelChangeDevNameAc = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel",nil) style:UIAlertActionStyleDefault handler:nil];
UIAlertAction *enterChangeDevNameAc = [UIAlertAction actionWithTitle:NSLocalizedString(@"enter",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

UITextField *newDeviceNameTF = changeDeviceNameDialog.textFields[0];
}];

[changeDeviceNameDialog addAction:cancelChangeDevNameAc];
[changeDeviceNameDialog addAction:enterChangeDevNameAc];
[changeDeviceNameDialog addTextFieldWithConfigurationHandler:^(UITextField *textField){
textField.delegate = self;
textField.placeholder = NSLocalizedString(@"new_device_name", nil);
textField.text = _prefixString;
}];
[self presentViewController:changeDeviceNameDialog animated:YES completion:nil];

// below refer the replay

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text isEqualToString:_prefixString] && range.location == _prefixString.length - 1 && range.length == 1) {
return NO;
}
return YES;
}

我想要的效果是弹出alert时,textfield有默认文本AAAA-,用户不能清除AAAA-文本。

用户可以输入其他文本附加 AAAA-。

但是像upper一样的delegate,我还是可以去掉前缀文本的。

最佳答案

试试这个,

设置你的prefixString,

self.prefixString = @"PREFIX";

然后在delegate方法中,

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

if ([textField.text isEqualToString:_prefixString] && range.location == _prefixString.length - 1 && range.length == 1) {

return NO;
}

return YES;
}

关于ios - 如何限制 iOS 中的前缀文本字段字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29695363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com