iOS - layoutIfNeeded没有在自定义UITableViewCell中创建框架

时间:2015-01-09 03:13:40

标签: ios uitableview autolayout

我这里有一个自定义tableview单元格的类,但在awakeFromNib中,self.frame始终为0,0,0,0。我试着打电话给[self layoutIfNeeded],但这没有效果。我需要框架将c放在单元格的正确位置。代码肯定会运行(我已经尝试过断点),为什么它不起作用?

#import "ChangeColourSubjectColourTableViewCell.h"
#import <QuartzCore/QuartzCore.h>

#define COLOUR_HEIGHT_DECIMAL 0.8
#define CORNER_RADIUS 6.0

@implementation ChangeColourSubjectColourTableViewCell

- (void)awakeFromNib {
    // Initialization code
    [self layoutIfNeeded];

    //Colour View
    //Size
    CGRect rect;
    rect.size.height = self.frame.size.height * COLOUR_HEIGHT_DECIMAL; //80% height
    rect.size.width = rect.size.height;

    //Position
    CGFloat gap = self.frame.size.height * (1 - COLOUR_HEIGHT_DECIMAL) / 2;
    rect.origin.y = gap;
    rect.origin.x = self.frame.size.width - rect.size.width - gap;

     UIView *c = [[UIView alloc] initWithFrame:rect];


    [c setBackgroundColor:[UIColor blackColor]];
    [c.layer setCornerRadius:CORNER_RADIUS];

    [self addSubview:c];
    _colourView = c;
}

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

    // Configure the view for the selected state
}

- (void)setColourViewColour:(UIColor *)colour {
    [_colourView setBackgroundColor:colour];
}

@end

1 个答案:

答案 0 :(得分:1)

从xib加载单元格时调用awakeFromNib方法,但是单元格的框架由tableview管理。

您应该在方法awakeFromNib中创建子视图作为变量,并覆盖方法setFrame / layoutSubviews以布置子视图,方法layoutSubviews中的cell.frame始终为true。

你可以这样做:

- (void)awakeFromNib {
    // Initialization code
    UIView *c = [[UIView alloc] initWithFrame:CGRectZero];
    [c setBackgroundColor:[UIColor blackColor]];
    [c.layer setCornerRadius:CORNER_RADIUS];
    [self addSubview:c];
    _colourView = c;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    //Colour View
    //Size
    CGRect rect;
    rect.size.height = self.frame.size.height * COLOUR_HEIGHT_DECIMAL; //80% height
    rect.size.width = rect.size.height;

    //Position
    CGFloat gap = self.frame.size.height * (1 - COLOUR_HEIGHT_DECIMAL) / 2;
    rect.origin.y = gap;
    rect.origin.x = self.frame.size.width - rect.size.width - gap;
    _colourView.frame = rect;
}

在iOS6或更高版本中,您可以使用

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell reloadUI];// you can do like this
}

// cell
- (void) reloadUI {
    CGRect rect;
    rect.size.height = self.frame.size.height * COLOUR_HEIGHT_DECIMAL; //80% height
    rect.size.width = rect.size.height;

    //Position
    CGFloat gap = self.frame.size.height * (1 - COLOUR_HEIGHT_DECIMAL) / 2;
    rect.origin.y = gap;
    rect.origin.x = self.frame.size.width - rect.size.width - gap;
    _colourView.frame = rect;
}