0

我在单元格上添加 UITextField。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:CellIdentifier];
}


myLoc = [[UITextField alloc] initWithFrame:CGRectMake(35, 10, 250, 40)];
myLoc.adjustsFontSizeToFitWidth = YES;
myLoc.textColor = [UIColor blackColor];
myLoc.textAlignment = UITextAlignmentCenter;
myLoc.placeholder = @"Enter Location";
myLoc.returnKeyType = UIReturnKeyDone;
myLoc.autocorrectionType = UITextAutocapitalizationTypeNone;
myLoc.tag = indexPath.row;
myLoc.delegate = self;
[myLoc setEnabled:YES];
[cell addSubview:myLoc];

return cell;
}

在 textFieldShouldReturn 中,我会将文本字段中的文本写入可变数组,并存储在 nsuserdefaults 中。

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

[myLoc resignFirstResponder];

[locationArray addObject:textField.text];
locName = [NSUserDefaults standardUserDefaults];
[locName setObject:locationArray forKey:@"textName"];
[locName synchronize];

NSLog(@"Done pressed %@",myLoc.text);

return YES;

}

...但是 myLoc.text 总是为空对我有什么想法吗?

4

3 回答 3

2

在委托方法中,不要使用myLoc引用文本字段,而是使用textField作为函数参数提供的实际指针。这个实际上应该指向正确的文本字段,因此 textField.text 应该具有正确的值。

附带说明:您在哪里定义myLoc?看起来您正在尝试在视图控制器上设置属性。这样,您将始终覆盖该属性。为此,您根本不需要属性,因此只需myLoc在函数范围内本地定义,例如UILabel *myLoc

于 2012-05-07T19:44:37.903 回答
1

你最好创建自己的自定义 UITableViewCell。您可以在此处查看如何创建一个: 教程

尝试使用现有的 UITableViewCell 充其量是困难的,最坏的情况是不可能的。您最好使用自定义单元格。

于 2012-05-07T19:48:34.863 回答
0

你的文本不应该是 NULL,因为它是一个 NSString。您确定您在谈论文本字段中的文本吗?

添加 NSLog(@%"@", textField.text); 时输出什么 到你的 shouldReturn 方法?

您确定您在文本字段中输入了吗?此外,即使不输入,您也应该得到 @"" 而不是 nil。

于 2012-05-07T19:44:15.353 回答