简体   繁体   English

将数据传递到自定义单元中的UIbutton

[英]Passing data to UIbutton in custom cell

I have a table view controller with custom cell. 我有一个带有自定义单元格的表视图控制器。 custom cell has got a button and some text label. 自定义单元格有一个按钮和一些文本标签。 How can i pass the text data of the row to the button when clicked? 单击时如何将行的文本数据传递给按钮?

1)In your cellForRowAtIndexPath: , assign button tag as index 1)在您的cellForRowAtIndexPath:中,将按钮标签分配为索引

cell.yourbutton.tag = indexPath.row;

2) Add target and action for your button as below. 2)为按钮添加目标和操作,如下所示。

[cell.yourbutton addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

3) Code to action based on index as below in ViewControler. 3)在ViewControler中根据索引编写代码以采取行动。

-(void)yourButtonClicked:(UIButton*)sender{
 [arrayOfTextVaule objectAtIndex:sender.tag];}

OR 要么

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
yourCustomCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"%@",selectedCell.label);}

Easy... add label text to button accessibilityValue and recover it in the target method. 容易...将标签文本添加到按钮accessibilityValue并在目标方法中恢复它。

{
    UIButton * button = [[UIButton alloc]init];
    button.accessibilityValue = label.text;
    [button addTarget:self action:@selector(sendLabelString:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)sendLabelString:(UIButton*)sender{
     NSString * labelString = sender.accessibilityValue;
}

The problem as I understand: 据我了解的问题:

  1. You have custom cell with a UILabel and UIButton 您具有带有UILabel和UIButton的自定义单元格
  2. On click, you want the title of the button to be the same as that of the label 单击时,您希望按钮的标题与标签的标题相同

The answer to the problem as just described: 刚才描述的问题的答案:

  1. You need to assign a tag to the label and the button so you can get a reference to them in the code. 您需要为标签和按钮分配标签,以便在代码中获得对它们的引用。 To do this: 去做这个:

    1.1. 1.1。 Go to the story board 转到故事板

    1.2. 1.2。 select the UILabel 选择UILabel

    1.3. 1.3。 from the properties, you can find the tag property, give it a number (like 1 for instance) 从属性中,您可以找到标签属性,并给它一个数字(例如1)

    1.4. 1.4。 Go through 1.1 through 1.3 for the UIButton (give it tag number 2). UIButton从1.1到1.3(给它标记2)。

  2. in the table view controller (the .m class file), add the following code: 在表视图控制器(.m类文件)中,添加以下代码:

     -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath]; // fetch an instance from the cell UILabel * lbl = (UILabel *) [cell viewWithTag: 1]; // fetch an instance of the label UIButton * btn = (UIButton *) [cell viewWithTag: 2]; // fetch an instance of the button btn.title = lbl.text; // I don't remember the text properties :D (figure it our yourself. it should be easy) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM