我正在尝试将“收藏夹按钮”添加到 UIableView 中的自定义单元格。
单元格有一个显示良好的标签和详细信息标签。我一定做错了什么,但我不知道它是什么。我的代码在下面,学习后改了原来的方法(注释)this question .
我的代码如下:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
}
cell.nameLabel.text = [myMutableArray valueForKey:@"Name"];
cell.detailLabel.text = [myMutableArray valueForKey:@"Detail"];
if (isFavorite)
{
NSLog(@"fave");
UIImage *btnImage = [UIImage imageNamed:@"goldStar.png"];
[cell.favoriteButton setImage:btnImage forState:UIControlStateNormal];
//[cell.favoriteButton setImage:[UIImage imageNamed:@"yellowStar.png"] forState:UIControlStateNormal];
} else {
NSLog(@"out of fave");
UIImage *btnImage = [UIImage imageNamed:@"greyStar.png"];
[cell.favoriteButton setImage:btnImage forState:UIControlStateNormal];
//[cell.favoriteButton setImage:[UIImage imageNamed:@"greyStar.png"] forState:UIControlStateNormal];
}
return cell;
}
MyCustomCell.h
@interface MyCustomCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@property (nonatomic, weak) IBOutlet UILabel *detailLabel;
@property (nonatomic, strong) IBOutlet UIButton *favoriteButton;
MyCustomCell.m
@implementation MyCustomCell
@synthesize nameLabel = _nameLabel;
@synthesize detailLabel = _detailLabel;
@synthesize favoriteButton = _favoriteButton;
- (void)awakeFromNib {
_favoriteButton = [[DBTileButton alloc] init];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
我已经检查过,按钮在 IB 中连接正常。提前感谢您的任何建议。
更新 我在日志消息中注意到图像帧设置为 0,0,0,0。我附上了自定义单元 IB 设置的照片。那里有什么不对劲吗?
最佳答案
据我所知,UIView 的任何子类的 IBOutlet 都不应该很强!无论如何,如果您想以编程方式初始化按钮,则无需使用 IBOutlet:起初,您忘记设置按钮的框架并通过 addSubview
将其添加到单元格 View 。但这是更简单的方法:只需在 Storyboard上添加按钮,设置自定义类并删除它:
_favoriteButton = [[DBTileButton alloc] init];
编辑:像图片一样为 Storyboard的按钮设置类
然后改变你的 socket :
@property (nonatomic, weak) IBOutlet DBTileButton *favoriteButton;
最后不要忘记将 socket 连接到您的按钮并以编程方式删除初始化。
关于ios - 为什么这个 UIButton 图像不会显示在自定义 UITableViewCell 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28839662/