我一直在第一次尝试表格视图,并且很难理解在执行操作时如何区分UI元素(如文本字段)细胞(例如按下按钮)。UITableView - 更改与正在按下按钮同一行上的文本字段
现在我在每一行都有一个按钮和一个文本字段。为了做到这一点:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"gameCell";
gameViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
long row = [indexPath row];
//Button to change text field
strokeUp = [UIButton buttonWithType:UIButtonTypeCustom];
strokeUp.frame = CGRectMake(248.0f, 11.0f, 80.0f, 32.0f);
[strokeUp setTag:indexPath.row];
[strokeUp addTarget:self action:@selector(addStroke:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:strokeUp];
//Text field that changes (puts '1' in box for now)
strokesBox = [[UITextField alloc] initWithFrame:CGRectMake(223.0f, 11.0f, 37.0f, 32.0f)];
strokesBox.delegate = self;
[strokesBox setTag:indexPath.row];
[cell.contentView addSubview:strokesBox];
return cell;
}
这就是我在点击strokeUp按钮时所做的。我希望与按钮位于同一行的文本字段显示'1'(稍后它会将1添加到框中的内容中)。根据用户在前一个屏幕中选择的行数,行数从2到6不等。
- (void)addStroke:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:table];
NSIndexPath *indexPath = [table indexPathForRowAtPoint:buttonPosition];
UIButton *senderButton = (UIButton *)sender;
if (senderButton.tag == 0)
{
NSLog(@"Row 1");
UITableViewCell *cell = [table cellForRowAtIndexPath:indexPath];
UITextField *sampleField = (UITextField *)[cell viewWithTag:0];
theTextField = @"1";
}
else if (senderButton.tag == 1) {
NSLog(@"Row 2");
UITableViewCell *cell = [table cellForRowAtIndexPath:indexPath];
UITextField *sampleField = (UITextField *)[cell viewWithTag:1];
sampleField.text = @"1";
}
}
它更好地使用自定义单元格,而不是像Jay Gajjar的答案那样在表格视图单元格中添加控件。 – Ganapathy