2011-07-12 178 views
0

我用customcell做了一个tableview。单元格包括标签和一个按钮。问题是,如何在按下按钮时检测标签的文本?Tableview自定义单元格按钮

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { 
    if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) { 
    // Initialization code 
     primaryLabel = [[UILabel alloc]init]; 
     primaryLabel.textAlignment = UITextAlignmentLeft; 
     primaryLabel.font = [UIFont systemFontOfSize:11]; 
     primaryLabel.backgroundColor = [UIColor clearColor]; 
     secondaryLabel = [[UILabel alloc]init]; 
     secondaryLabel.textAlignment = UITextAlignmentLeft; 
     secondaryLabel.font = [UIFont systemFontOfSize:9]; 
     secondaryLabel.backgroundColor = [UIColor clearColor]; 
     myImageView = [[UIImageView alloc]init]; 

     btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     btn.backgroundColor = [UIColor clearColor]; 

     [self.contentView addSubview:btn]; 
     [self.contentView addSubview:primaryLabel]; 
     [self.contentView addSubview:secondaryLabel]; 
     [self.contentView addSubview:myImageView]; 
    } 

    return self; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    return cell; 
} 
+0

这并不难,但这取决于你如何设置单元格。您可以向我们展示您创建单元格,标签和按钮的代码吗? – sosborn

+0

我也有一个提醒功能,我必须捕捉单元格内容并设置日历的事件控制器。 – Ulvi

回答

0

你正在寻找的方法是 - addTarget:动作:forControlEvents:

使用你比如你有一个UIButton,BTN,让我们说,你有你叫myAction自定义单元格的动作。代码如下所示:

[btn addTarget:self action:myAction forControlEvents:UIControlEventTouchUpInside]; 

因为myAction是您的单元格中的方法,所以您可以轻松访问标签属性。如果你需要把不同的控制你的行动:

[btn addTarget:otherController action:myAction forControlEvents:UIControlEventTouchUpInside]; 

在这种情况下,你将有一个参考保持在控制你的电池。既然你可能有多个单元格,你可以保留一个NSMutableArray作为属性,并在构建表格时添加单元格。

+0

感谢您的回答。我会尝试。 – Ulvi

相关问题