2011-09-16 8 views
5

ラベルやコントロールの高さはテキストに基づいて計算できます。このように:高さに基づいてテキストを取得する

NSString *[email protected]"fwfgwefgwefhwefhwoefhwoeifhoiwefhwoeifhwieofhweohfiweofowefhowefhoweifhweofhweofhweoihfweiofhiowefhweiofhwioefhweiofhiweofhweiofhweiofhweiofhweiofweoifiweofhweoifhiowefhoiwefhowewoefoiwehfoiwe";  
    labelsize=[text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 2000.0)]; 
    NSLog(@"labelsize.height%f",labelsize.height); 

ここでは高さ= 270と仮定します。今私は200の高さにあるテキストだけを欲しい。私のラベルの高さは200で、200の高さのテキストがラベルになり、残りのテキストが別のラベルに表示されるまで、私のラベルの高さは200です。ですから、私は高さに基づいてテキストを取得することが可能かどうか尋ねたいと思います。

ありがとうございます!

+0

はもしかして、あなたは、ラベルの高さに応じて、テキストのフォントサイズを取得したいと思いますか? –

+0

テキストのフォントサイズが固定されていないので、特定の高さに固定できるテキストだけが必要です。 – Gypsa

+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

必要に応じて、ラベルテキストを変更することができます。ここに私のサンプルコードです。

NSMutableString *tmpLabel2=[[NSMutableString alloc]init]; 
NSString *[email protected]"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); 

}

関連する問題