本文介绍了如何计算 UILabel 上 NSString 的宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,在 UILabel Width 和 Height 上动态生成 NSString.我试过:

I am working on a project to make the NSString on UILabel Width and Height dynamically.I tried with:

NSString *text = [messageInfo objectForKey:@"compiled"];
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
               constrainedToSize:constraint
                   lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"sizewidth = %f, sizeheight = %f", size.width, size.height);
NSLog(@"writerNameLabel.frame.size.width 1 -> %f",writerNameLabel.frame.size.width);
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];

CGRect labelFram = writerNameLabel.frame;
labelFram.origin.x = cell.frame.size.width - writerNameLabel.frame.size.width - 80;
writerNameLabel.frame = labelFram;
NSLog(@"writerNameLabel.frame.size.width 2-> %f",writerNameLabel.frame.size.width);

请看绿色气泡而不是灰色气泡.还是不对.

Please see the green bubble not the grey one.Still not right.

气泡代码

bubbleImageView.frame = CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, writerNameLabel.frame.size.width+15, writerNameLabel.frame.size.height+5);

请多多指教!谢谢!

推荐答案

那是因为你没有复用表格单元格,结构应该是这样的:

That's because you did not reuse the table cell, the structure should be like:

NSString *text = [messageInfo objectForKey:@"compiled"];
if(cell == nil)
        {
     writerNameLabel.numberOfLines = 0;
     writerNameLabel.textAlignment = UITextAlignmentRight;
     writerNameLabel.backgroundColor = [UIColor clearColor];
     [cell addSubview:writerNameLabel];
}
else {
     writerNameLabel = (UILabel *)[cell viewWithTag:WRITER_NAME_LABEL_TAG];
}
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
               constrainedToSize:constraint
                   lineBreakMode:UILineBreakModeWordWrap];
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];

我已经完成并回答了您的一些问题,这是编写 tableview 控制器的正确方法.你的问题将得到解决.

I've been gone through and answered some of your question, that's correct way to write your tableview controller. And your problem will be solved.

这篇关于如何计算 UILabel 上 NSString 的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:55