我正在使用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个字符。还尝试了其他委托方法

预期产量:
{
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 event,我建议将选择器添加为
[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/

10-13 04:09
查看更多