UI Button为nil,obj c

时间:2018-08-01 00:58:42

标签: ios objective-c xcode

在我的cellForRowAtIndexPath:方法中,我试图将按钮的tag设置为等于indexPath.row。但是,按钮为nil,因此tagnil

有人知道为什么吗?这是我在视图控制器单元中创建的按钮。

编辑:我的postCell不为零。只有与单元格关联的按钮为nil 和 我试图在VolunteerOpportunityCell中分配并初始化收藏夹按钮,特别是在awakeFromNib方法中。但这不允许我调用alloc方法。

3 个答案:

答案 0 :(得分:1)

您不应致电dequeueReusableCellWithIdentifier。它可以返回nil,在这种情况下,您的postCellnil,与此相关的所有内容都是nil。您不会检查它是否为零,因此您显然不了解有关dequeueReusableCellWithIdentifier的工作原理。但这没关系,因为您不应该首先调用它。

请致电dequeueReusableCellWithIdentifier:forIndexPath:。它永远不会是nil。它将提供一个单元,现在您将有机会配置该单元。

答案 1 :(得分:0)

首先,检查您的reuse id,以查看注册的reuse id是否为@"postCell"。如果是这样,请确保正确分配了favoritedButton。也就是说,如果单元是从.xib文件初始化的,则检查连接;如果不是,请检查favoritedButton的创建位置。

答案 2 :(得分:0)

第一点,请检查如何创建此VolunteerOpportunityCell类。当然,在Objective-C中,有两种.xib文件或手写代码的方法。因此,您应该在加载方法上知道两者的不同。 /> 我创建一个测试项目以确认我的答案。
我认为您可以使用.xib文件创建此favoriteButton。您可以执行此操作。

  VoulunteerOpportunityCell *postCell = (VoulunteerOpportunityCell *)[tableView dequeueReusableCellWithIdentifier:@"postCell"];
if (postCell == nil) {
    postCell = [[VoulunteerOpportunityCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"postCell"];
    NSArray *nib =[[NSBundle mainBundle]loadNibNamed:@"VoulunteerOpportunityCell" owner:self options:nil];
    postCell = (VoulunteerOpportunityCell *)[nib objectAtIndex:0];
}

postCell.tag = indexPath.row;
postCell.favoritedButton.tag = indexPath.row;
NSLog(@"indexPath.row-%ld,post.tag:%ld",indexPath.row,postCell.favoritedButton.tag);

因此您可以粘贴我的代码以尝试一下!

如果使用手写代码,则必须在favoritedButton中初始化VoulunteerOpportunityCell

相关问题