ios - 根据 Text 动态获取 UILabel 的高度返回不同的 iOS 7.0 和 iOS 6.1 值

标签 ios iphone objective-c ios6 ios7

我正在使用此方法动态获取 UILabel 的高度:

+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size:  (CGSize)LabelSize{
    label.numberOfLines = 0;
    CGSize labelSize = [label.text sizeWithFont:fontForLabel constrainedToSize:LabelSize lineBreakMode:NSLineBreakByCharWrapping];
    return (labelSize);
}

如果我的代码在低于 iOS 8 的系统上运行,我将通过此解决方案获得 UILabel 的确切大小 但是如果我在 iOS7 上运行我的应用程序,那么它会返回一个不同的值。

最佳答案

您必须动态设置框架,如下所示:

Tested on iOS 6 to iOS 12.2

swift :

let constrainedSize = CGSize(width: self.titleLable.frame.size.width, height:9999)

let attributesDictionary = [NSAttributedString.Key.font: UIFont.init(name: "HelveticaNeue", size: 11.0)]

let string = NSAttributedString.init(string: "textToShow", attributes: attributesDictionary as [NSAttributedString.Key : Any])

var requiredHeight = string.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, context: nil)


if (requiredHeight.size.width > self.titleLable.frame.size.width) {
    requiredHeight = CGRect(x: 0, y: 0, width: self.titleLable.frame.size.width, height: requiredHeight.size.height)
}
var newFrame = self.titleLable.frame
newFrame.size.height = requiredHeight.size.height
self.titleLable.frame = newFrame

Objective-C :

CGSize constrainedSize = CGSizeMake(self.resizableLable.frame.size.width  , 9999);

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
                                      nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary];

CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
    requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.resizableLable.frame;
newFrame.size.height = requiredHeight.size.height;
self.resizableLable.frame = newFrame;

关于ios - 根据 Text 动态获取 UILabel 的高度返回不同的 iOS 7.0 和 iOS 6.1 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20068849/

相关文章:

ios - 如何快速检查设备的互联网连接是否不佳

iphone - 如何从单 View 应用程序启动 cocos2D 游戏

ios - <__NSCFDictionary : 0x1557f400> was mutated while being enumerated.'

ios - 如何使用可选的 URL 参数为 GET 请求映射不同的 JSON 响应

iphone开发-分析错误

IOS 照片框架

ios - MTKView - 一次绘制两个 View

ios - Xcode 按钮 (IBAction) 只工作一次

iphone - 在 requestFinished 方法中调用方法时崩溃?

iphone - iOS 从另一个 View Controller 加载 UIWebView 中的网页