对UITableViewCell进行子类化会导致文本和图像在加载时移位

时间:2012-10-30 17:11:50

标签: ios cocoa-touch uitableview

我创建了UITableViewCell的子类,因为我想明确设置imageView帧大小,而不管我实际给它的图像大小。

话虽这么说,当我的tableView加载时,一切似乎在瞬间转变。图像稍微变大,titleLabeldetailLabel都会移近图像。我的子类中做错了什么?

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Selected View
        self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
        self.selectedBackgroundView.backgroundColor = RGB(233, 233, 233);

        // Text Label
        self.textLabel.textColor = [UIColor darkGrayColor];
        self.textLabel.opaque = YES;
        self.textLabel.highlightedTextColor = self.textLabel.textColor;

        // Detail
        self.detailTextLabel.font = [UIFont systemFontOfSize:12.0];
        self.detailTextLabel.numberOfLines = 3;
        self.detailTextLabel.opaque = YES;
        self.detailTextLabel.highlightedTextColor = self.detailTextLabel.textColor;

        // Cell
        self.opaque = YES;
    }
    return self;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


- (void)layoutSubviews {
    [super layoutSubviews];

    float desiredWidth = 70;
    float desiredHeight = 70;
    float leftMargin = 5;
    float topMargin = 5;

    float w=self.imageView.frame.size.width;
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.clipsToBounds = YES;
    if (w>desiredWidth) {
        float widthSub = w - desiredWidth;
        self.imageView.frame = CGRectMake(leftMargin,topMargin,desiredWidth,desiredHeight);
        self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x-widthSub,self.textLabel.frame.origin.y,self.textLabel.frame.size.width+widthSub,self.textLabel.frame.size.height);
        self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x-widthSub,self.detailTextLabel.frame.origin.y,self.detailTextLabel.frame.size.width+widthSub,self.detailTextLabel.frame.size.height);

    }
}

1 个答案:

答案 0 :(得分:0)

我看到你在做什么

self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];

我真的认为它应该是

self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.bounds];

因为self.selectedBackgroundView基于父视图坐标系

定位