获取iOS 7中的NSString高度 [英] Get the NSString height in iOS 7
本文介绍了获取iOS 7中的NSString高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码从字符串长度计算标签的高度。我使用的是xcode 5.0,它在iOS 6模拟器中运行良好但在iOS 7中效果不佳。
I am using the below code to calculate the height of a label from string length. Im using xcode 5.0 and it works fine in iOS 6 simulator but it's not working well in iOS 7.
NSString* str = [[array objectAtIndex:i]valueForKey:@"comment"];
CGSize size = [className sizeWithFont:[UIFont systemFontOfSize:15]
constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
Height_1 = size.height;
如果iOS 7有任何解决方案,请提供帮助。
先谢谢
If there is any solution for iOS 7 then please help. Thanks in Advance
推荐答案
这里有一个我用来计算iOS 6和iOS 7高度的解决方案,我已经通过了几个参数来使它可以重复使用。
Well here is a solution I use for calculating the height for iOS 6 and iOS 7, and I have passed few arguments to make it reusable.
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
/**
* This method is used to calculate height of text given which fits in specific width having font provided
*
* @param text Text to calculate height of
* @param widthValue Width of container
* @param font Font size of text
*
* @return Height required to fit given text in container
*/
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
CGFloat result = font.pointSize + 4;
if (text)
{
CGSize textSize = { widthValue, CGFLOAT_MAX }; //Width and height of text area
CGSize size;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
//iOS 7
CGRect frame = [text boundingRectWithSize:textSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:font }
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
}
else
{
//iOS 6.0
size = [text sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
}
result = MAX(size.height, result); //At least one row
}
return result;
}
希望这有帮助,是的任何建议都表示赞赏。快乐编码:)
Hope this helps and yes any suggestions are appreciated. Happy Coding :)
对于iOS 7及以上版本,请使用以下方法。
For iOS 7 and above use below method.
+ (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
//iOS 7
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height + 1);
}
return size;
}
这篇关于获取iOS 7中的NSString高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文