首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS: UILabel动态高度使用sizeWithFont:constrainedToSize:lineBreakMode: not working

问iOS: UILabel动态高度使用sizeWithFont:constrainedToSize:lineBreakMode: not working
EN

Stack Overflow用户
提问于 2011-04-05 06:59:01
回答 2查看 18.2K关注 0票数 4

我试图给我的UILabel动态高度,这样我的其他标签的布局在横向和纵向上看起来都是正确的。

在纵向,我的文本换行到第二行,而在横向,它没有。因此,当使用sizeWithFont:constrainedToSize:lineBreakMode:时,当我假设文本为2行时,我会得到相同的高度,而这是一个更大的数字。

当我的UILabel有两行或更多行文本(纵向)时,我如何获得它的高度,以及当它处于横向时,如何获得一行的新高度?

我想我不明白如何让动态高度工作...

代码语言:javascript
复制
UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, top, screen.size.width - 20, 200.0f)];
itemTitle.text = self.newsAsset.title;
itemTitle.adjustsFontSizeToFitWidth = NO;
itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
itemTitle.font = [UIFont boldSystemFontOfSize:18.0];
itemTitle.textColor = [UIColor blackColor];
itemTitle.shadowColor = [UIColor whiteColor];
itemTitle.shadowOffset = CGSizeMake(0, 1);
itemTitle.backgroundColor = [UIColor blueColor];
itemTitle.lineBreakMode = UILineBreakModeWordWrap;
itemTitle.numberOfLines = 0;
[itemTitle sizeToFit];

// Set the height
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize titleSize = [itemTitle.text sizeWithFont:itemTitle.font constrainedToSize:maximumLabelSize lineBreakMode:itemTitle.lineBreakMode];

NSLog(@"Height: %.f  Width: %.f", titleSize.height, titleSize.width);

//Adjust the label the the new height
CGRect newFrame = itemTitle.frame;
newFrame.size.height = titleSize.height;
itemTitle.frame = newFrame;

// Add them!
[headerView addSubview:itemTitle];
[itemTitle release];

top += titleSize.height;
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-05 07:27:39

将maximumLabelSize设置为的行更改为

代码语言:javascript
复制
CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX);
票数 3
EN

Stack Overflow用户

发布于 2011-04-05 07:13:50

在您现在的代码中,无论在哪个方向上,您都将获得相同的宽度和高度,因为您始终将宽度300传递给sizeWithFont方法。如果您将其设置为动态,也许sizeWithFont的结果也会动态更改。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5545275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档