How to get other control value from UITableViewCell?

二次信任 提交于 2019-12-07 18:36:44

问题


I have one doubt that how to get other control's value when we select a row or tap on button while having custom tableViewCell. Suppose I have a TableView Cell with a TextField, a Slider and button. Button has action using:

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

Now I can get button on its action method. I need to get textField's value and slider's value on button tap.

The one option is I create a array and store values for these two control in that array and manage this. But I don't think this is correct way to manage it.

Please navigate me to the currect way to get value of UITableViewCell's subview's value.

Thanks


回答1:


While creating your textfield and slider, give them a constant tag and then add to cell's contentView

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

and then in your buttonTapped: method

-(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];
}



回答2:


Whenever you create subviews (button , text field etc. ) for your UITableViewCell don't forget to tagged them.

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

Once you tagged, you could access them using below method.

- (UIView *)viewWithTag:(NSInteger)tag

When you select,you could get the subviews of your UITableViewCell's by using ViewWithTag function of UIView.

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


来源:https://stackoverflow.com/questions/6000350/how-to-get-other-control-value-from-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!