[英]Tableview custom cell button
I made a tableview with customcells.我用customcells做了一个tableview。 Cells include labels and a button.
单元格包括标签和按钮。 The question is, how can i detect the label's text when its button is pressed?
问题是,当按下按钮时如何检测标签的文本?
- (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;
}
The method you are looking for is – addTarget:action:forControlEvents:您正在寻找的方法是 – addTarget:action:forControlEvents:
Using you example, you have a UIButton, btn, and let's say you have an action in your custom cell called myAction.以您为例,您有一个 UIButton,btn,假设您在自定义单元格中有一个名为 myAction 的操作。 The code would look like this:
代码如下所示:
[btn addTarget:self action:myAction forControlEvents:UIControlEventTouchUpInside];
Because myAction is a method in your cell, you can easily access the label property.因为 myAction 是您的单元格中的一个方法,您可以轻松访问 label 属性。 If you need to put your action in a different controller:
如果您需要将您的操作放在不同的 controller 中:
[btn addTarget:otherController action:myAction forControlEvents:UIControlEventTouchUpInside];
In this case you will have to keep a reference to your cell in the controller.在这种情况下,您必须在 controller 中保留对您的单元格的引用。 Since you probably have more than one cell you could keep an NSMutableArray as a property and add your cells as you build your table.
由于您可能有多个单元格,您可以将 NSMutableArray 作为属性保留并在构建表格时添加单元格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.