gpt4 book ai didi

iphone - UITextField 限制字符的数量和类型

转载 作者:技术小花猫 更新时间:2023-10-29 10:32:28 25 4
gpt4 key购买 nike

我有两个文本字段,我想限制字符的数量和类型。我已使用以下代码位分别执行每个功能,但找不到在同一功能内执行这两项操作的方法。

限制字符类型:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Only characters in the NSCharacterSet you choose will insertable.
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}

并限制字符数:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 10 && range.length == 0)
return NO;
return YES;
}

最佳答案

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= 10 && range.length == 0)
return NO;
// Only characters in the NSCharacterSet you choose will insertable.
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}

已编辑

如果你想为第三个文本字段添加不同的条件,那么你可以这样做。
为第三个文本字段创建引用 thirdField

然后用这个

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == thirdField) {
//your contion e.g
if (textField.text.length < 7) {
return YES;
} else {
return NO;
}
}
else {
if (textField.text.length >= 10 && range.length == 0)
return NO;
// Only characters in the NSCharacterSet you choose will insertable.
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefgABCDEFG"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
}

关于iphone - UITextField 限制字符的数量和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265625/

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