UITextLabel在UITableViewCell中的大小

时间:2013-12-30 22:59:35

标签: ios objective-c uitableview uilabel textlabel

我仅通过覆盖UITableViewCell方法将-(void)layoutSubviews子类化:

-(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];

}

在单元格内部,我还在UIStepper方法中添加了- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath子视图:

- (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
}

但是,当textLabel的文字太长时,它似乎会挤掉detailTextLabel。我想知道为什么会发生这种情况,因为我已经为这些子视图指定了帧。 enter image description here

提前谢谢!

2 个答案:

答案 0 :(得分:1)

好的,我通过手动设置框架的CGRect解决了这个问题:

-(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];

}

感谢@Bamsworld。

答案 1 :(得分:0)

正如评论中所推测的那样[super layoutSubviews]正在改变标签的框架,而你只是在改变宽度。