制作多行 UILabel 从顶部而不是中间开始文本

发布于 2024-10-20 11:42:39 字数 147 浏览 6 评论 0原文

我对多行 UILabel 有一个小问题,我的 UILabel 文本奇怪地从中间开始,当新行到达时它会上升,因此最后一行始终位于中间。我希望它的行为像普通的文本视图一样,从顶部开始,各行在彼此下方,第一行保持在顶部。抱歉,如果我解释得不好,如果需要的话我可以尝试详细说明!提前致谢!

I have a little problem with multiline UILabel, my UILabel text like starts from the middle strangely and it goes up when new lines arrive so that the last line is on the middle always. I want it to behave like a normal textview, starting from top and lines going under each other, first line staying on top. Sorry if I explained it badly, I can try to elaborate if needed! Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巷雨优美回忆 2024-10-27 11:42:39

您可以使用 NSString 上的 sizeWithFont:constrainedToSize:lineBreakMode: 方法来计算给定字体和约束宽度的文本块的高度。然后,您将更新标签的框架,使其足够大以包含文本。

CGSize textSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);

You can use the sizeWithFont:constrainedToSize:lineBreakMode: method on NSString to figure out the height of a block of text given a font and a constrained width. You would then update the frame of your label to be just large enough to encompass the text.

CGSize textSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);
屌丝范 2024-10-27 11:42:39

由于 sizeWithFont 方法在 iOS 7.0 + 中已弃用,因此您可以使用名为 boundingRectWithSize 的替代方法。

例如:

NSDictionary *attrsDictionary =[NSDictionary dictionaryWithObject:YourFont forKey:NSFontAttributeName];
NSAttributedString *attrString =[[NSAttributedString alloc] initWithString:yourString attributes:attrsDictionary];

textRect = [attrString boundingRectWithSize:yourSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

Since sizeWithFont method is decprecated in iOS 7.0 +, you can use a alternative method named boundingRectWithSize.

For Example:

NSDictionary *attrsDictionary =[NSDictionary dictionaryWithObject:YourFont forKey:NSFontAttributeName];
NSAttributedString *attrString =[[NSAttributedString alloc] initWithString:yourString attributes:attrsDictionary];

textRect = [attrString boundingRectWithSize:yourSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文