我制作了自定义UITableViewCell并将UIImageView添加到该单元格。
然后,当我构建时,该应用程序会终止并显示以下日志消息。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NewsCell setImageView:]: unrecognized selector sent to instance 0x109139f80'

我有这个代码。

ViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[NewsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                cell.imageView.image = [UIImage imageNamed:@"abcde.jpg"];
                break;
        }
    }
    return cell;
}

NewsCell.h
@interface NewsCell : UITableViewCell

@property (nonatomic, strong) UIImageView* imageView;
@property (nonatomic, strong) UILabel* titleLabel;

@end

NewsCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 44, 40)];
        [self.contentView addSubview:self.imageView];
        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 5, 200, 25)];
        self.titleLabel.font = [UIFont systemFontOfSize:24];
        [self.contentView addSubview:self.titleLabel];
    }
    return self;
}

如何解决它以将自定义单元格反映到tableView?

最佳答案

转到 NewsCell.h ,您是否在 imageView 上看到警告?问题是您正在尝试将只读属性替换为 readwrite属性。但它不允许您这样做。

您想确切地执行当前正在执行的操作,可以尝试声明不同的imageView,例如:

NewsCell.h

@interface NewsCell : UITableViewCell

@property (nonatomic, strong) UIImageView* imageView2;
@property (nonatomic, strong) UILabel* titleLabel;

@end

NewsCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
    self.imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 44, 40)];
    [self.contentView addSubview:self.imageView2];
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 5, 200, 25)];
    self.titleLabel.font = [UIFont systemFontOfSize:24];
    [self.contentView addSubview:self.titleLabel];
}
return self;
}

对于 ViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 static NSString *CellIdentifier = @"Cell";
NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[NewsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0) {
    switch (indexPath.row) {
        case 0:
            cell.imageView2.image = [UIImage imageNamed:@"abcde.jpg"];
            break;
    }
}
return cell;
}

08-05 22:44