iPad 上的自定义 UITableViewCell 宽度错误

Custom UITableViewCell is wrong width on iPad

我创建了一个自定义 UITableViewCell,但是当我 运行 我的应用程序在 iPad 上时,单元格的内容与 iPhone 上的宽度相同。我想要内容 - 例如背景 UIView - 是完整的宽度。

customCell.h

#import <UIKit/UIKit.h>

@interface customCell : UITableViewCell

@property (nonatomic, strong) UILabel *title;
@property (nonatomic, strong) UILabel *description;
@property (nonatomic, strong) UIView *background;

@end

customCell.m

#import "customCell.h"

@implementation customCell

@synthesize title = _title;
@synthesize description = _description;
@synthesize background = _background;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // configure background
        self.background = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, 115.0f)];

        // configure title
        self.title = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, self.contentView.frame.size.width-10, 70)];
        self.title.textAlignment = NSTextAlignmentNatural;
        self.title.lineBreakMode = NSLineBreakByWordWrapping;
        self.title.numberOfLines = 4;
        self.title.preferredMaxLayoutWidth = 20;
        self.title.adjustsFontSizeToFitWidth = NO;
        self.title.textColor = [UIColor whiteColor];
        self.title.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:16];

        [self.background addSubview:self.title];

        // configure description
        self.description = [[UILabel alloc] initWithFrame:CGRectMake(5, 80, self.contentView.frame.size.width-10, 20)];
        self.description.textColor = [UIColor whiteColor];
        self.description.textAlignment = NSTextAlignmentLeft;
        self.description.font = [UIFont fontWithName:@"SourceSansPro-Bold" size:13];

        [self.background addSubview:self.description];

        [self addSubview:self.background];
        [self sendSubviewToBack:self.background];
    }

    return self;
}

@end

我做错了什么?

单元格的大小尚未在 initWithStyle:reuseIdentifier: 方法中设置。使用适当的 autoresizingMask 值设置子视图或实施单元格的 layoutSubviews 方法来更新它们的大小。

此外,由于您将 titledescription 标签添加到 background 视图,因此标签的大小应基于 background 视图的大小,而不是单元格 contentView.

的大小

最后,永远不要命名 属性 description。它会与继承自NSObjectdescription方法冲突。