iOS 获取字符串的高度和宽度

2017-12-19  本文已影响0人  花蕊1235

方法1:

CGRectlabelsize =[@"门店已接单,用户取消订单"boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-150,2000)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:@{NSFontAttributeName:Font(14)}context:nil];

state= [[UILabelalloc]initWithFrame:CGRectMake(CGRectGetMaxX(pate.frame) +6,10, labelsize.size.width,14)];

方法2:

- (void)viewDidLoad {

[super viewDidLoad];

//获取字符串的宽度

NSLog(@"获得字符串的宽度:%f",[self widthForString:@"我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!"fontSize:10.0 andHeight:10.0]);

//获取字符串的高度

NSLog(@"获得字符串的宽度:%f",[self heightForString:@"我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!"fontSize:10.0 andWidth:10.0]);

}

#pragma -mark -functions

//获取字符串的宽度

-(float) widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height

{

CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置

returnsizeToFit.width;

}

//获得字符串的高度

-(float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width

{

CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置

returnsizeToFit.height;

}

上一篇下一篇

猜你喜欢

热点阅读