iphone - 在 iOS 7 中获取 NSString 高度

标签 iphone ipad nsstring cgsize

我使用下面的代码根据字符串长度计算标签的高度。我使用的是 xcode 5.0,它在 iOS 6 模拟器中运行良好,但在 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 的任何解决方案,请提供帮助。 提前致谢

最佳答案

这是我用来计算 iOS 6 和 iOS 7 高度的解决方案,我传递了一些参数以使其可重用。

#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;
}

希望这有帮助,是的,任何建议都会受到赞赏。快乐编码:)

对于 iOS 7 及以上版本,请使用以下方法。

+ (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;
}

关于iphone - 在 iOS 7 中获取 NSString 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014062/

相关文章:

iphone - 如何检查 UITextfield 中是否有文本?

ios拖拽库

ios - NSString boundingRectWithSize 返回不必要的高度

iphone - 从 MVC (iOS) 中的异步操作返回结果

iphone - 当 UIImageView.image 设置 2-3 次时应用程序崩溃

iphone - 如何获取按计算值排序的托管对象

ios - 用 NSFileManager 替换 CoreData persistantStore 是否安全?

iphone - 在 IOS 6 中设置 UITableView 的背景颜色

ios - 复杂的正则表达式文本修改

iphone - 从 UIPickerView 的选定行设置 UIButton 的标题