UITableView从单元格获取标签文本

时间:2014-05-27 09:03:33

标签: iphone objective-c xcode

我有UITableView问题 1.我在单元格中创建标签,在行中创建单元格,在各个部分中创建行,现在我在每个单元格中添加按钮,这样我就可以获得警告消息框,其中显示该单元格的标签文本,其中存在按钮 我已尽力做到这一点,但无法获得确切标签的文字,但问题是我得到了错误标签的文字

- (IBAction)myShow:(id)sender
{
    NSLog(@"%@",*****what to pass in here*****);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我有这个

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
         mysampleimage = [[UIImageView alloc]initWithFrame:CGRectMake(3,3, 40, 40)];
         mysampleimage.image=[UIImage imageNamed:@"a.png"];
         mysampleimage.tag=13;
         [cell.contentView addSubview:mysampleimage];

         myButton = [[UIButton alloc]init];
         myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
         myButton.frame = CGRectMake(165, 10, 65, 30.);
         [myButton setTitle:@"Show" forState:UIControlStateNormal];
         myButton.tag = 14;
         [cell addSubview:myButton];

         lbl = [[UILabel alloc]initWithFrame:CGRectMake(50, 6, 200, 43)];
         lbl.tag=12;
         [cell.contentView addSubview:lbl];
     }
     else
     {
         lbl=(UILabel *)[cell.contentView viewWithTag:12];
         mysampleimage=(UIImageView *)[cell.contentView viewWithTag:13];
         myButton = (UIButton *)[cell.contentView viewWithTag:14];
     }

     myButton.accessibilityLabel = lbl.text;

     [myButton addTarget:self action:@selector(myShow:) forControlEvents:UIControlEventTouchUpInside];
     return cell;


}

2 个答案:

答案 0 :(得分:0)

在tableviews中使用按钮的想法是将标记作为indexpath.row附加,然后使用选择器中的sender.tag获取数据。

在您的情况下,您可以按如下方式获取文本:

- (IBAction)myShow:(id)sender
{
    UIButton *button = (UIButton*) sender;
    UILabel *label = [button.superView viewWithTag:12];


    NSLog(@"%@",label.text);
    //Implement alert here.
}

答案 1 :(得分:0)

[myButton addTarget:self action:@selector(myShow:) forControlEvents:UIControlEventTouchUpInside];

由于您重复使用单元格,在单元格init之外添加添加操作,它将导致将manay操作添加到单元格。这就是警报显示错误文本的原因。您需要子类化UITableViewCell,将上面的代码移动到单元格init方法,并在subClassCell中实现动作选择器。

相关问题