- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *test = @"印象人家民俗院占地面积500平方米,有8间客房16张床可同时接待24人住宿、1间厨房操作间、1间餐厅、1间储物间。饭庄选用纯天然食材,特色美食香草饼。 乐在小酒窝主题客栈位于北京市密云县太师屯镇车道峪民俗村内,为村东桥头路南第一家。主旨以“品窖酒、住民俗、享快乐”的精神态度为顾客提供休闲服务,拥有特色小窝9间,,";
//这地方最重要的也是要设置属性字符串 否则计算出来的高度不对
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:test];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;//调整行间距 这个跟计算高度的行间距一定要对应
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [test length])];
self.testLabel.attributedText = attributedString;
// [self.testLabel sizeToFit];
CGRect rect = [self boundsWithFontSize:14 text:test needWidth:300];
self.testLabel.frame = CGRectMake(10, 70, 300, rect.size.height);
}
- (CGRect)boundsWithFontSize:(CGFloat)fontSize text:(NSString *)text needWidth:(CGFloat)needWidth{
NSString *str = text;
if (str.length<=0) {
str= @"";
}
// str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
// str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
// str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
// str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
// str = [str stringByReplacingOccurrencesOfString:@"," withString:@""];
// str = [str stringByReplacingOccurrencesOfString:@"。" withString:@""];
// str = [str stringByReplacingOccurrencesOfString:@"、" withString:@""];
NSLog(@"str-----%@",str);
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 5;
UIFont *font = [UIFont systemFontOfSize:fontSize];
[attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
[attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(needWidth, CGFLOAT_MAX) options:options context:nil];
NSLog(@"size:%@", NSStringFromCGSize(rect.size));
if ((rect.size.height - font.lineHeight) <= style.lineSpacing) {
if ([[self class] containChinese:str]) { //如果包含中文
rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-style.lineSpacing);
}
}
return rect;
}
//判断如果包含中文
+ (BOOL)containChinese:(NSString *)str {
for(int i=0; i< [str length];i++){
int a = [str characterAtIndex:i];
if( a > 0x4e00 && a < 0x9fff){
return YES;
}
}
return NO;
}