我正在使用 UICollectionview,每个单元格都有 UITextfield,我试图从每个文本字段获取完整的字符串并保存到字典中。我使用了以下代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField.tag==100) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
}
if (textField.tag==101) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
}
}
我试过:
使用上面的代码我能够正确设置字符串,但是,如果我删除字符,则不会调用上述方法并且不会更新字典。
TextFieldDidBeginEditing 调用最初只能记录 1 个字符。还尝试了其他委托(delegate)方法
预期输出:
{
image_0001: All Character,
image_0002: A
}
任何帮助都会被投票。谢谢。
最佳答案
textField shouldChangeCharactersInRange
在 text field
实际更改其文本之前被调用,如果您需要获取更新值,则执行此操作
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField.tag==100) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0001"];
}
else if (textField.tag==101) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"image_0002"];
}
}
更新的答案
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString * currentStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField.tag==100) {
[m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0001"];
}
else if (textField.tag==101) {
[m11ThumbImage_MutCaptionDictionary setValue:currentStr forKey:@"image_0002"];
}
return YES;
}
替代方式
在你的 viewdidload 中添加要获取 EditingChanged textfield 事件
,我建议将选择器添加为
[textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
随着文本字段值的更改,您将从这个 textChanged:
选择器中获得更改后的值。
-(void)textChanged:(UITextField *)textField
{
NSLog(@"textfield data %@ ",textField.text);
if (textField.tag==100) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0001"];
}
else if (textField.tag==101) {
[m11ThumbImage_MutCaptionDictionary setValue:[textField.text stringByAppendingString:string] forKey:@"image_0002"];
}
}
关于ios - 将 UITextfield 中的每个字符记录到 IOS 中的 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133318/