我们都知道我们可以根据文字计算标签或任何控件的高度。像这样:
NSString *text=@"fwfgwefgwefhwefhwoefhwoeifhoiwefhwoeifhwieofhweohfiweofowefhowefhoweifhweofhweofhweoihfweiofhiowefhweiofhwioefhweiofhiweofhweiofhweiofhweiofhweiofweoifiweofhweoifhiowefhoiwefhowewoefoiwehfoiwe";
labelsize=[text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 2000.0)];
NSLog(@"labelsize.height%f",labelsize.height);
现在假设我得到身高= 270。现在我只想要那个高度为200的文本。就像我的标签高度是200,我希望直到200高度文本进入标签,文本的其余部分应显示在另一个标签。所以我想问一下是否有可能根据身高得到文本。
提前致谢!
答案 0 :(得分:3)
CGFloat maxHeight = 500;
NSString *text = @"fwfgwefgwefhwefhwoefhwoeifhoiwefhwoeifhwieofhweohfiweofowefhowefhoweifhweofhweofhweoihfweiofhiowefhweiofhwioefhweiofhiweofhweiofhweiofhweiofhweiofweoifiweofhweoifhiowefhoiwefhowewoefoiwehfoiwe";
NSMutableString *tmpText = [[NSMutableString alloc] initWithString:text];
NSRange range = NSMakeRange([tmpText length] - 1, 1);
while ([text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 2000.0)].height > maxHeight) {
[tmpText deleteCharactersInRange:range];
range.location--;
}
NSLog(@"result: %@", tmpText);
[tmpText release];
我认为这可以胜任。它没有经过全面测试,但确实有效。
答案 1 :(得分:1)
根据您的需要,您可以根据自己的兴趣更改标签文字。这是我的示例代码。
NSMutableString *tmpLabel2=[[NSMutableString alloc]init];
NSString *text=@"Hello friend what r u doin..? what is going on in your company.. Tell me something yar i want to meet with u whenever u free just call me i will be der ok rest is perfect. talk u later…";
NSMutableString *tmpLabel1 = [[NSMutableString alloc] initWithString:text];
NSRange range = NSMakeRange([tmpLabel1 length] - 1, 1);
CGSize labelsize=[text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 2000.0) lineBreakMode:UILineBreakModeWordWrap];
while ([tmpLabel1 sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 2000.0)].height > 200) {
unichar Char=[tmpLabel1 characterAtIndex:[tmpLabel1 length]-1];
NSString*strTemp=[NSString stringWithFormat:@"%C",Char];
[tmpLabel2 insertString:strTemp atIndex:0];
[tmpLabel1 deleteCharactersInRange:range];
range.location--;
}
label.frame=CGRectMake(50, 50, labelsize.width, 200);
label.text=tmpLabel1;
label.font=[UIFont fontWithName:@"Arial" size:14];
label.numberOfLines=0;
label.clipsToBounds=YES;
label.adjustsFontSizeToFitWidth=YES;
label.lineBreakMode=UILineBreakModeCharacterWrap;
label.backgroundColor=[UIColor grayColor];
NSLog(@"first Label is: %@", tmpLabel1);
NSLog(@"Second Label is: %@", tmpLabel2);
}