我一直在第一次嘗試表格視圖,並且很難理解在執行操作時如何區分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