Sizes of UITextLabel inside UITableViewCell

308 views Asked by At

I have subclassed UITableViewCell by only overriding the -(void)layoutSubviews method:

-(void)layoutSubviews {
    [super layoutSubviews];  //The default implementation of the layoutSubviews
    
    CGRect textLabelFrame = self.textLabel.frame;
    textLabelFrame.size.width = 180;
    self.textLabel.frame = textLabelFrame;
    self.textLabel.textAlignment = NSTextAlignmentLeft;
    self.textLabel.adjustsFontSizeToFitWidth = YES;
    
    CGRect detailTextLabelFrame = self.detailTextLabel.frame;
    detailTextLabelFrame.size.width = 30;
    self.detailTextLabel.frame = detailTextLabelFrame;
    self.detailTextLabel.textAlignment = NSTextAlignmentLeft;
    self.detailTextLabel.adjustsFontSizeToFitWidth = YES;
    
    [self sizeToFit];

}

Inside the cell, I have also added a UIStepper subview in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// code omitted   
    UITableViewCell *cell;
    if(indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:OrderCellIdentifier forIndexPath:indexPath];
        if ( cell == nil ) {
            cell = [[GinkgoDeliveryOrderCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:OrderCellIdentifier];
            UIStepper * stepper = [[UIStepper alloc] initWithFrame:CGRectMake(113, 7, 94, 29)];
            [cell addSubview:stepper];
        }
// code omitted
}

However, when the text for textLabel is too long, it seems to squeeze away the detailTextLabel. I am wondering why this is happening as I have already specify the frames for these subviews. enter image description here

Thank you in advance!

2

There are 2 answers

0
Bamsworld On BEST ANSWER

As speculated in the comments [super layoutSubviews] is altering the frames of your labels and you are only changing the width.

0
Ra1nWarden On

Ok, I have solved the problem by manually setting the CGRectfor the frame:

-(void)layoutSubviews {
    [super layoutSubviews];  //The default implementation of the layoutSubviews

    self.textLabel.frame = CGRectMake(15, 11, 180, 21);
    self.textLabel.textAlignment = NSTextAlignmentLeft;
    self.textLabel.adjustsFontSizeToFitWidth = YES;

    CGRect detailTextLabelFrame = CGRectMake(280, 11, 40, 21);
    self.detailTextLabel.frame = detailTextLabelFrame;
    self.detailTextLabel.textAlignment = NSTextAlignmentCenter;

    [self sizeToFit];

}

Thanks to @Bamsworld.