UITableViewCell与UITextField失去了选择UITableView行的能力?

Fab*_*eri 15 iphone cocoa-touch objective-c uitableview ios

我差不多完成了UITableViewCell一个UITextField用它来实现.而不是经历CGRectMake,UITableViewCell.contentView我已经以更简单的方式实现它:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
    amountField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 190, 30)];
    amountField.placeholder = @"Enter amount";
    amountField.keyboardType = UIKeyboardTypeDecimalPad;
    amountField.textAlignment = UITextAlignmentRight;
    amountField.clearButtonMode = UITextFieldViewModeNever; 
    [amountField setDelegate:self];

    [[cell textLabel] setText:@"Amount"];
    [cell addSubview:amountField];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

然后我还实现了该didSelectRow方法,重新设置textField以允许显示其他字段的输入视图.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [amountField resignFirstResponder];
    ...
}
Run Code Online (Sandbox Code Playgroud)

这很顺利,只有表中还有其他行,当选择其他行时,整个单元格被选中并变成蓝色,而我的UITextField没有,我的意思是选择了字段,我可以输入文字但是没有选择单元格.我测试了它并发现问题在于:

[cell addSubview:amountField];
Run Code Online (Sandbox Code Playgroud)

这似乎打破了可选择的单元格行为,甚至添加它[cell contentView]都不能解决这个问题.我错过了什么?

Emp*_*ack 44

如果文本字段的userInteractionEnabled设置为YES,并且它填充整个单元格,则无法让单元格听取触摸.为了让单元格响应触摸,您需要将文本字段的userInteractionEnabled设置为NO.

编辑:如果要使文本字段可编辑,则在选择单元格时,在didSelectRowAtIndexPath:方法中添加以下代码,

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // get the reference to the text field
    [textField setUserInteractionEnabled:YES];
    [textField becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*gle 6

你没有通过添加子视图来破坏任何东西,而是UITextField在UITableViewCell之前捕获触摸.您可以通过点击UITextField外部但在UITableViewCell的范围内进行测试,您会看到它确实仍然按照您的预期进行选择.

为了解决这个问题,你可以继承UITextField并添加一个UITableView属性.在实例化UITextField时设置属性并将其添加到单元格.

amountField.tableView = tableView;
Run Code Online (Sandbox Code Playgroud)

然后你需要覆盖子类中的becomeFirstResponder,并在方法中获取具有UITextField的单元格的行,然后手动选择它

- (BOOL)becomeFirstResponder
{
    // Get the rect of the UITextView in the UITableView's coordinate system
    CGRect position = [self convertRect:self.frame toView:self.tableView];
    // Ask the UITableView for all the rows in that rect, in this case it should be 1
    NSArray *indexPaths = [self.tableView indexPathsForRowsInRect:position];
    // Then manually select it
    [self.tableView selectRowAtIndexPath:[indexPaths objectAtIndex:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    return YES;
}
Run Code Online (Sandbox Code Playgroud)