iOS 进阶iOS开发

iOS 计算字符串长度-boundingRectWithSize

2018-01-25  本文已影响572人  李琪_59dc

iOS 7.0之前用sizeWithFont:(计算的不是很准确)

CGFloat width1=[(NSString *)obj sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(1000, FONTHEIGHT)].width;

iOS 7.0之后用 boundingRectWithSize:
返回文本绘制所占据的矩形空间。

CGFloat width1=[(NSString *)obj boundingRectWithSize:CGSizeMake(1000, FONTHEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width;

特殊情况

1、如果使用上述方法计算出结果后,将字符串赋值给UILabel显示,会遇到“宽度计算感觉是够的,但是字符串就是没显示完全”的情况。

#import <UIKit/UIKit.h>
//.h文件
@interface LyLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets textInsets; // 控制字体与控件边界的间隙
@end
//.m文件
#import "LyLabel.h"

@implementation LyLabel

- (instancetype)init {
    if (self = [super init]) {
        _textInsets = UIEdgeInsetsZero;
    }
    return self;
}
//重写方法
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _textInsets = UIEdgeInsetsZero;
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}

@end

具体应用:

LyLabel *testLabel    = [[LyLabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.f, 24.0f)];
testLabel.backgroundColor = [UIColor whiteColor];
testLabel.textColor       = [UIColor blackColor];
testLabel.font            = [UIFont systemFontOfSize:16.0f];
testLabel.textInsets      = UIEdgeInsetsMake(0.f, 15.f, 0.f, 0.f); // 设置左内边距(上、左、下、右)

总结一下,方便以后查看QAQ

上一篇 下一篇

猜你喜欢

热点阅读