救命! uitableviewcell buttonpressed更新文本字段

时间:2011-03-15 23:50:02

标签: iphone ios ipad uitableview

我想按下QTY按钮(红色文本)并将文本(即13)复制到同一行的文本字段中。

here is my sample uitableviewcell

-(IBAction)qtyButtonPressed:(id)sender {

UITextField *textField = (UITextField *)[self.view viewWithTag:3];

textField.text = @"13";

这就是我所拥有的。

3 个答案:

答案 0 :(得分:1)

如果每个单元格都有一个按钮,首先您需要能够识别单击哪一行的按钮。通常,如果它是一个包含1个部分的表,则可以将行号设置为cellForRowAtIndexPath中的按钮标记值:...当单元格可见时设置

[button setTag:indexPath.row];

然后在按下按钮时调用的选择器中,获取标记值以确定行号,并为该行中的textfield设置文本

  int row = [sender tag];
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row section:0];
  id cell = [tableView cellForRowAtIndexPath:indexPath];
  [cell.textField setText:....];

要使其工作,您需要子类化UITableViewCell,并使用property / synthesize访问button和textField。

答案 1 :(得分:1)

我知道这已经得到了解答,但我遇到了类似的问题,不幸的是我使用了标签来查找表格视图单元格中的字段,允许我在InterfaceBuilder / Xcode中进行布局,仍然可以避免像这样的子类: / p>

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
    static NSString *AttributeCellIdentifier = @"AttributeCell";
    UITableViewCell *cell;
    UILabel *label;
    UITextField *value;
    MyAttribute *a;

    switch( indexPath.section ) {
        case ATTRIBUTES_SECTION:
            cell = [tableView dequeueReusableCellWithIdentifier: AttributeCellIdentifier];
            label = (UILabel *) [cell viewWithTag: 1];
            value = (UITextField *) [cell viewWithTag: 2];
            a = [attributeList objectAtIndex: indexPath.row];
            label.text = a.label;
            value.text = a.value;
            break;
        // Other sections...
    }
    return cell;
}

但这意味着我不能将标签用于文本字段所在的行。因此,作为使用标签的替代方法,我使用文本字段中的坐标来查看它所在的行:

- (void) textFieldDidEndEditing: (UITextField *) textField {
    NSLog( @"Entering %s with %@", __func__, textField );
    NSIndexPath *textFieldLocation = [self.tableView indexPathForRowAtPoint: [textField convertPoint:textField.bounds.origin toView: self.tableView]];
    NSLog( @"- The textfield is in the cell at: %@", textFieldLocation );

    if( textFieldLocation.section == ATTRIBUTES_SECTION ) {
        MyAttribute *a = [attributeList objectAtIndex: textFieldLocation.row];
        a.value = textField.text;
    }
}

如果我在单元格中有多个文本字段,我仍然可以使用标记值来知道哪一个正在结束编辑。

构建一个返回任何视图的tableview索引的小帮助方法甚至可能是明智的:

- (NSIndexPath *) indexPathForView: (UIView *) view {
    NSIndexPath *loc = [self.tableView indexPathForRowAtPoint: [view convertPoint: view.bounds.origin toView: self.tableView]];
    return loc;
}

这可以放在一个类别中,并且可以轻松地用于任何tableview,无需任何编码。

答案 2 :(得分:0)

您可以在带有addTarget:action:forControlEvents:的按钮上使用UIControlEventTouchUpInside来注册触摸按钮时将被调用的选择器。然后在该方法中,找到相应的文本字段并分配其text属性。

相关问题