【问题标题】:How to increase UILabel hight according to text in UITableView?如何根据 UITableView 中的文字增加 UILabel 高度?
【发布时间】:2015-08-11 11:44:45
【问题描述】:

我为我的UITableView 创建了一个自定义单元格。在该单元格的 .m 文件中,在

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

我已经创建了一个这样的标签。

self.lblMsg=[[UILabel alloc] initWithFrame:CGRectMake(15.0, self.lblWeatherTitle.frame.origin.y+self.lblWeatherTitle.frame.size.height, size.width-5.0, 50.0)];
    dm.homeMessagelblwidth=size.width-5.0;

    [self.lblMsg setNumberOfLines:0];
    [self.lblMsg setFont:[UIFont systemFontOfSize:15.0]];
    [self.lblMsg setMinimumScaleFactor:12.0];
    [self.lblMsg setLineBreakMode:NSLineBreakByWordWrapping];
    [self.imgvwMSGBG addSubview:self.lblMsg];

从我的另一个视图控制器类中的cellforrowAtIndex 委托中设置的文本。

该文本没有固定长度。我要做的是根据文本更改self.lblMsgself.imgvwMSGBG 高度。而且我还需要增加hightForRowAtIndex 代表下的行高。如何根据文字增加标签、UIImage 和行高。

【问题讨论】:

  • 简而言之,使用自动布局,否则您在编写时的代码已过时

标签: ios objective-c uitableview uilabel custom-cell


【解决方案1】:

最好的方法是使用自调整单元格方法。你应该做下一个:

1.为UITableView设置estimatedRowHeight和rowHeight:

- (void)viewDidLoad
{
   ...
   self.tableView.estimatedRowHeight = 100.0;
   self.tableView.rowHeight = UITableViewAutomaticDimension;
}

2.在单元格子类中为self.lblMsgself.imgvwMSGBG设置自动布局约束:

UIView *label = self.lblMsg;
UIView *background = self.imgvwMSGBG;
NSDictionary *views = NSDictionaryOfVariableBindings(label, background);

[self.imgvwMSGBG addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"V:|-[label]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];
[self.imgvwMSGBG addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"H:|-[label]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];

[self.contentView addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"V:|-[background]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];
[self.contentView addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"H:|-[background]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];

【讨论】:

    【解决方案2】:

    这就是我的工作。

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
        int myHt = 100;
        UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 100, 1000, 80)];
        if ([localize(@"myLang") isEqualToString:@"en"]) {
            commentLabel.textAlignment = NSTextAlignmentLeft;
        } else {
            commentLabel.textAlignment = NSTextAlignmentRight;
        }
        commentLabel.numberOfLines = 0;
        commentLabel.text = [NSString stringWithFormat:@"%@", [[actualProductsArray objectAtIndex:indexPath.row] valueForKey:@"Comment"]];
        commentLabel.textColor = [UIColor colorWithRed:57/255.0 green:57/255.0 blue:57/255.0 alpha:1.0];
        commentLabel.font = [UIFont fontWithName:localize(@"myFontName") size:40];
        [commentLabel sizeToFit]; // this is very important step
    
        myHt = myHt + commentLabel.frame.size.height + (10);
    
        return myHt;
    }
    

    【讨论】:

      【解决方案3】:

      试试这个

      -(CGSize)heightForLabelText:(NSString*)labelText withWidth:(float)width andFontSize:(float)size
      
      {
      
          UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:size];
      
          CGSize constraintSize = CGSizeMake(width, MAXFLOAT);
      
          NSDictionary * attributes = @{NSFontAttributeName:cellFont};
      
          NSStringDrawingContext *context     = [[NSStringDrawingContext alloc] init];
      
          CGRect rect = [labelText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:context];
      
      //    NSLog(@"%@ -- (h,w)=(%f,%f)", labelText,rect.size.height,rect.size.width);
      
          return rect.size;
      
      }
      //Usage
          [self heightForLabelText:myLabelText withWidth:300.0 andFontSize:14.0f];
      

      【讨论】:

        【解决方案4】:

        这里是方法请使用正确的字体和字体大小

        > + (CGFloat) calculateHeight:(NSString *) message withFont:(UIFont *) font withLabelWidth:(CGFloat)width {
        >     CGFloat varHeight       =  0;
        >     NSString *trimmedString =  [message stringByTrimmingCharactersInSet:[NSCharacterSet
        >                                                                     whitespaceAndNewlineCharacterSet]];
        >     if(trimmedString.length>0)
        >     {
        >         CGSize maximumLabelSize     = CGSizeMake(width, 9999);
        >         CGRect textRect             = [message boundingRectWithSize:maximumLabelSize options:
        >                                        NSStringDrawingUsesLineFragmentOrigin
        > attributes:@{NSFontAttributeName:font} context:nil];
        >         varHeight                   = ceilf(textRect.size.height);
        >     }
        >     return varHeight; }
        

        【讨论】:

          【解决方案5】:
          //use this for custom font
          CGFloat width =  [label.text sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]].width;
          
          //use this for system font 
          CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;
          
          label.frame = CGRectMake(point.x, point.y, width,height);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多