【问题标题】:How to get other control value from UITableViewCell?如何从 UITableViewCell 中获取其他控件值?
【发布时间】:2011-05-14 07:11:09
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

    标签: iphone uitableview custom-cell


    【解决方案1】:

    在创建文本字段和滑块时,给它们一个常量标签,然后添加到单元格的 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];
    }
    

    【讨论】:

    • 我在使用该代码时遇到错误。看起来 contentview 函数的定义是:@property (nonatomic, readonly, retain) UIView *contentView;
    【解决方案2】:

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

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

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

    - (UIView *)viewWithTag:(NSInteger)tag
    

    当你选择时,你可以使用UIViewViewWithTag函数来获取你的UITableViewCell的子视图。

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
        {
            UITableViewCell *cell = [tableview cellForRowAtIndexPath:indexPath];
            UITextField* myTextField = [cell  viewWithTag:0];
            UILabel* myTextLabel     = [cell  viewWithTag:1];
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2018-07-16
      相关资源
      最近更新 更多