2

我有一个疑问,当我们在自定义 tableViewCell 时选择一行或点击按钮时如何获取其他控件的值。假设我有一个带有 TextField、Slider 和按钮的 TableView Cell。按钮具有使用以下功能:

btn.tag = indexPath.row;
[btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

现在我可以在其操作方法上获得按钮。我需要在点击按钮时获取 textField 的值和滑块的值。

一个选项是我创建一个数组并将这两个控件的值存储在该数组中并管理它。但我不认为这是管理它的正确方法。

请导航到获取 UITableViewCell 子视图值的正确方法。

谢谢

4

2 回答 2

6

在创建文本字段和滑块时,给它们一个常量标签,然后添加到单元格的 contentView

textfield.tag= TEXTFIELDTAG; //TEXTFIELDTAG = 100 or any other constant
[cell.contentView addSubview:textfield];

然后在你的 buttonTapped: 方法中

-(void)buttonTapped:(id)sender
{

    int row = ((UIButton*)sender).tag;
    NSIndexPath* indexpath = [NSIndexPath indexPathForRow:row inSection:0]; // in case this row in in your first section
    UITableViewCell* cell = [table cellForRowAtIndexPath:indexPath];
    UITextField* textfield = [cell.contentView viewWithTag:TEXTFIELDTAG];
}
于 2011-05-14T07:32:17.493 回答
2

每当您为您创建子视图(按钮、文本字段等)时,UITableViewCell不要忘记标记它们。

myTextField.tag = 0;
myTextLabel.tag = 1; 
[cell addSubview:myTextField];
[cell addSubview:myTextLabel];

标记后,您可以使用以下方法访问它们。

- (UIView *)viewWithTag:(NSInteger)tag

当您选择时,您可以ViewWithTag使用UIView.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableview cellForRowAtIndexPath:indexPath];
        UITextField* myTextField = [cell  viewWithTag:0];
        UILabel* myTextLabel     = [cell  viewWithTag:1];
    }
于 2011-05-14T07:28:21.490 回答