根据UILabel动态调整uitableViewCell的大小(带段落间距) [英] Dynamically size uitableViewCell according to UILabel (With paragraph spacing)

查看:82
本文介绍了根据UILabel动态调整uitableViewCell的大小(带段落间距)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITableView,它由JSON文件中的文本和图像填充. TableView单元格当前针对文本中不包含很多换行符的帖子"正确调整大小,但是我无法获得它来为4个或5个换行符的帖子"计算正确的高度.

I have a UITableView which is populated by text and images from a JSON file. The TableView Cell is currently sizing correctly for "posts" that do not contain many line breaks in the text however I cannot get it to calculate the correct height for "posts" with 4 or 5 line breaks.

获取身高的代码:

-(float)height :(NSMutableAttributedString*)string
{
  NSString *stringToSize = [NSString stringWithFormat:@"%@", string];

  CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);

  CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:contraint lineBreakMode:NSLineBreakByWordWrapping];

  return size.height;
}

如何在允许换行和留白的同时计算正确的尺寸?

How do I calculate the correct size while allowing for line breaks and white space?

其余方法

在TableView的CellForRow内部:

Inside of TableView CellForRow:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *row = [NSString stringWithFormat:@"%i", indexPath.row];

float postTextHeight = [self height:postText];

NSString *height = [NSString stringWithFormat:@"%f", heightOfPostText + 70];

[_cellSizes setObject:height forKey:row];
}

表格单元格的高度:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *imageHeightString = [NSString stringWithFormat:@"%@", [_cellSizes objectForKey:indexPath.row]];

float heightOfCell = [imageHeightString floatValue];

 if (heightOfCell == 0) {

    return 217;
};

return heightOfCell + 5;
}

推荐答案

最好先计算高度,方法中不要包括高度计算部分:

better u need to calculate the height first, don't include the height calculation part in method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

更好地使用方法进行计算:

Better to calculate it in method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

由于您正在从json获取数据,因此您很容易进行计算 在"heightForRowAtIndexPath"方法中.

since u are getting the data from json it is easy for u to calculate in the "heightForRowAtIndexPath" method.

下面的代码将给出示例,以根据需要更改文本的高度. 希望这对你有帮助:)

follwing code will give the example to calculate height of text change it ur requirement. hopee this helps u :)

// i am using an array 
- (void)viewDidLoad
{
   [super viewDidLoad]; 
   // Do any additional setup after loading the view, typically from a nib.

   UIFont *labelFont = [UIFont fontWithName:@"Noteworthy-Bold" size:20];
   NSDictionary *arialdict = [NSDictionary dictionaryWithObject:labelFont forKey:NSFontAttributeName];

   NSMutableAttributedString *message = [[NSMutableAttributedString alloc] initWithString:@"this is just the sample example of how to calculate the dynamic height for tableview cell which is of around 7 to 8 lines. you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];

   array = [NSMutableArray arrayWithObjects:message, nil];
   NSMutableAttributedString *message_1 = [[NSMutableAttributedString alloc] initWithString:@"you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];
  [array addObject:message_1];   
}

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
     return 2;
 }

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return 2;
 }


 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *Cell = [self.aTableView dequeueReusableCellWithIdentifier:@"cell"];
   if(Cell == nil)
    {
       Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
     }

     //dont include the height calculation part hear, becz heights are already set for all the cell 
    [Cell.textLabel sizeToFit];
    Cell.textLabel.attributedText = [array objectAtIndex:indexPath.row]; // dont calculate height hear it will be called after "heightForRowAtIndexPath" method
    Cell.textLabel.numberOfLines = 8;
    return Cell;
 }

  // put ur height calculation method i took some hardcoded values change it :)
  -(float)height :(NSMutableAttributedString*)string
 {
    /*
      NSString *stringToSize = [NSString stringWithFormat:@"%@", string]; 
  // CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);
     CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height //set the constant width, hear MAXFLOAT gives the maximum height

     CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:20.0f] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
return size.height; //finally u get the correct height
    */
     //commenting the above code because "sizeWithFont: constrainedToSize:maxSize: lineBreakMode: " has been deprecated to avoid above code use below

    NSAttributedString *attributedText = string;
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){225, MAXFLOAT}
                           options:NSStringDrawingUsesLineFragmentOrigin
                              context:nil];//you need to specify the some width, height will be calculated
    CGSize requiredSize = rect.size;
    return requiredSize.height; //finally u return your height
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     //whatever the height u need to calculate calculate hear only    
     CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]];
     NSLog(@"%f",heightOfcell);
     return heightOfcell;
 }

希望这对您有帮助:)

对于 SWIFT 版本

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate 
{

var messageArray:[String] = [] //array to holde the response form son for example 
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background",
                    "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.", 
                    " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.",
                    ]
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1;
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return messageArray.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell;
    if(cell == nil)
    {
        cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: "CELL")
        cell?.selectionStyle = UITableViewCellSelectionStyle.None
    }
    cell?.textLabel.font = UIFont.systemFontOfSize(15.0)
    cell?.textLabel.sizeToFit()
    cell?.textLabel.text = messageArray[indexPath.row]
    cell?.textLabel.numberOfLines = 0
    return cell!;
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row])
    return height + 70.0
}

func calculateHeightForString(inString:String) -> CGFloat
{
    var messageString = inString
    var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)]
    var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
    var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
    var requredSize:CGRect = rect
    return requredSize.height  //to include button's in your tableview

 }
}

这篇关于根据UILabel动态调整uitableViewCell的大小(带段落间距)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆