我在故事板中设置了单元格原型,我想选择它来执行特定操作。 这是我的代码;
'
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"ProjectCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell){
UILabel *titleLabel = (UILabel *)[cell viewWithTag:101];
titleLabel.text = @"New York";
UIImageView *mainImage = (UIImageView *)[cell viewWithTag:102];
[mainImage setImage:[UIImage imageNamed:@"nyc_temp.png"]];
UITextView *descText = (UITextView *)[cell viewWithTag:103];
[descText setText:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua..."];
UIButton *selectButton = (UIButton *)[cell viewWithTag:104];
[selectButton addTarget:self action:@selector(selectButtonPressed) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)selectButtonPressed//:(id)sender withEvent:(UIEvent *)event
{
NSLog(@"");
}
'
从不调用 selectButtonPress。 我知道选择按钮是正确的按钮,因为我可以在viewWithTag行下方更改文本,背景颜色等,为什么目标不会粘住?
更新:我已经更改了我的代码以使用自定义单元格类,但仍然没有运气,并且正如一个人建议的那样,明确地将按钮投射到 UIButton(我本来会想到这不应该是必需的?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"TemplateTableViewCell";
TemplateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if(cell){
UILabel *titleLabel = (UILabel *)[cell viewWithTag:101];
titleLabel.text = @"New York";
[cell.mainImage setImage:[UIImage imageNamed:@"nyc_temp.png"]];
[cell.desc setText:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua..."];
[cell.selectButton setUserInteractionEnabled:YES];
[(UIButton *)cell.selectButton addTarget:self action:@selector(selectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)selectButtonPressed:(id)sender
{
NSLog(@"");
}
仍然不起作用,除了能够设置目标方法之外,我可以通过其他所有方式与按钮进行交互。 这与触摸层次结构有关吗?
代码设置表格视图单元格按钮的操作
[(UIButton *)[cell.contentView viewWithTag:104] addTarget:self action:@selector(selectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
并像这样定义方法 发送者
-(void)selectButtonPressed:(id)sender
{
NSLog(@"Method called");
}
如果您在原型单元格中创建了 selectButton,则所有子视图都将添加到表视图单元格的容器视图中,因此要获得带有标签的所需按钮,您必须调用如下:
[(UIButton *)[cell.contentView viewWithTag:104] addTarget:self action:@selector(selectButtonPressed) forControlEvents:UIControlEventTouchUpInside];
并确保你已经为你selectButton
tag
104
值,并检查你没有给任何其他视图104 tag
值。
事实证明,CELL用户在代码的另一部分被错误地禁用了,这阻止了任何触摸输入。