工作记录 - 字符串长度计算

问题记录:在开发中,列表控件的UILabel的高度需要动态适应,这是需要根据实际的文字来计算label文字的宽高从而来实现cell的高低适应。

NSString *info = @"但是公司的高度是广东省公司的广东省高速度来开个大帅哥多撒谎个爱好就跟他说噶三公司噶是的刚好是我哥如果黑暗如果坏都干撒降低公司及嘎斯进欧冠赛欧结果就赛欧国际韶关;可垃圾费;阿尔加两块;三个身高萨嘎干撒的公司的高度上收到公司的公司都给ID搜狗破is打个屁偶是东莞IP手动皮革是滴哦苹果是滴哦苹果度搜皮为欧公司的漂漂是第三个是干撒噶是的噶虽然刚撒旦个撒公司的公司的高度";;

    CGSize infoSize = CGSizeMake(tableView.frame.size.width, 1000);
    
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f ]};
    //默认的
  CGRect infoRect =   [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    // 参数1: 自适应尺寸,提供一个宽度,去自适应高度
    // 参数2:自适应设置 (以行为矩形区域自适应,以字体字形自适应)
    // 参数3:文字属性,通常这里面需要知道是字体大小
    // 参数4:绘制文本上下文,做底层排版时使用,填nil即可
    
     //上面方法在计算文字高度的时候可能得到的是带小数的值,如果用来做视图尺寸的适应的话,需要使用更大一点的整数值.取整的方法使用ceil函数
    return height + ceil(infoRect.size.height);

链接:http://www.jianshu.com/p/d7f7f01818f2

设置 UILabel 的 Frame 高度

在设置 UILabel 的 Frame 高度时,不能简单的设置为字体的 font size。否则会将字体的一部分裁剪掉。因为 UILabel 在不同的字体设置下,对 Frame 的高度要求也不一样,大多数情况下都比Font的高度设置要高一些。

一、sizeThatFits

使用 view 的 sizeThatFits 方法。
// return 'best' size to fit given size. does not actually resize view. Default is return existing view size

  • (CGSize)sizeThatFits:(CGSize)size;
例子:
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
NSLog(@"size = %@", NSStringFromCGSize(size));

输出:size = {246.33333333333334, 36}

二、sizeToFit

使用 view 的 sizeToFit 方法。
注意:sizeToFit 会改变 view 原来的 bounds,而 sizeThatFits 不会。
// calls sizeThatFits: with current view bounds and changes bounds size.

  • (void)sizeToFit;
例子
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
[testLabel sizeToFit];
NSLog(@"size = %@", NSStringFromCGSize(testLabel.frame.size));

输出:size = {246.33333333333334, 36}

三、sizeWithAttributes

使用 NSString 的 sizeWithAttributes 方法。

  • (CGSize)sizeWithAttributes:(nullable NSDictionary *)attrs NS_AVAILABLE(10_0, 7_0);
例子
NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGSize size = [text sizeWithAttributes:@{
NSFontAttributeName : font
}];
NSLog(@"size = %@", NSStringFromCGSize(size));

输出: size = {246.3134765625, 35.80078125}

四、boundingRectWithSize

使用 NSString 的 boundingRectWithSize 方法。

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);

来源:
http://www.genshuixue.com/i-cxy/p/15281292

你可能感兴趣的:(工作记录 - 字符串长度计算)