如何找出截断的 UILabel 文本的宽度

发布于 2024-09-26 21:24:31 字数 245 浏览 10 评论 0原文

我有 UILabel,其中包含动态文本。有时文本太长而无法显示,因此会自动截断。如何找出截断文本可见部分的宽度?

sizeThatFits 返回未截断文本的长度,因此目前我只能检测何时完成截断。需要知道有多少是可见的,包括那三个点。有什么建议吗?

澄清:当文本被截断时,它通常比 UILabel 宽度短。

I have UILabel, which contains dynamic text. Sometimes text is too long to be shown and thus automagically truncated. How do I find out width of the visible part of truncated text?

sizeThatFits returns length of untruncated text, so at the moment I can only detect when truncation will be done. Need to know how much is visible, including those three dots. Any tips?

Clarification: when text is truncated, it's usually shorter than UILabel width.

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

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

发布评论

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

评论(2

梦冥 2024-10-03 21:24:31

机器人K是正确的。

如果我是您,我会执行以下操作:

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 24)];
  label.text = @"this is some really long text that i want in a small label";
  [view addSubview:label];

  CGSize size = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size  
                 lineBreakMode:label.lineBreakMode];

这应该给您一个小于 200 的值(考虑到受约束的最大大小和截断方法)。

Robot K is correct.

If I was you I'd do the following:

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 24)];
  label.text = @"this is some really long text that i want in a small label";
  [view addSubview:label];

  CGSize size = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size  
                 lineBreakMode:label.lineBreakMode];

This should give you a value less than 200 (taking into account the constrained max size and truncation method).

无所谓啦 2024-10-03 21:24:31

我不明白为什么如果文本被截断,宽度会与 UILabel 的宽度不同。无论如何,您可以使用 sizeWithFont:constrainedToSize: 计算具有给定字体但限于“约束大小”的字符串的大小。

I don't understand why the width would be different that the width of the UILabel if the text is being truncated. Regardless, you can use sizeWithFont:constrainedToSize: to calculate the size of a string with a given font but limited to a "constraining size".

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