如何更改 UILabel 中的截断字符?
当 UILabel
的文本被截断时,默认情况下会插入 3 个点。 是否可以更改或禁用这些字符?
When the text of a UILabel
gets truncated there are 3 dots inserted by default.
Is it possible to change these characters or disable them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我编写了一个自定义截断类,您可以将其弹出到代码中的任何位置。只需使用下面这个方法即可。如果发生截断,它将返回 true,如果您只想使用标签默认帧宽度,则 MaxWidth 可以保留为 0。将 maxWidth 设置为小于帧宽度,以在其帧范围内缩短它。
Swift 2 (带有一些用于转换的 swift 3 注释)
用法:
class:
Objective C
class:
I have written a custom truncating class that you can pop into you code where ever. Just use this method below. it will return true if truncation has taken place, and MaxWidth can be left as 0 if you just want to use the labels default frame width. Put maxWidth as something less than the frames width to shorten it within its frames bounds.
Swift 2 (with some swift 3 comments for converting)
usage:
class:
Objective C
class:
查看
-[UILabel setLineBreakMode:]
和UILineBreakModeCharacterWrap
。-[UILabel lineBreakMode]
的默认值为UILineBreakModeTailTruncation
,这会导致末尾出现省略号。Look at
-[UILabel setLineBreakMode:]
andUILineBreakModeCharacterWrap
. The default value of-[UILabel lineBreakMode]
isUILineBreakModeTailTruncation
, which causes the ellipsis at the end.正如 Javanator 所说,你必须自己进行截断。你应该使用
UIKit 上向
NSString
类添加的sizeWithFont:forWidth:lineBreakMode:
消息,用于获取具有特定字体的字符串的宽度。这将处理所有类型的字体。链接
As Javanator said you would have to do your own truncation. You shuld use the
sizeWithFont:forWidth:lineBreakMode:
message on the UIKit additions toNSString
class to get the width of a string with a certain font. This will handle all types of fonts.Link
您还可以设置
,这样就不需要截断文本,您可以在
标签
上显示完整的文本。You can also set
With this there will be no need of truncating text and you can display the complete text on your
label
.我想提供 Fonix 之前提供的更 Swifty 版本并使用 Swift 5 语法。我还决定将这些函数编写为 UILabel 的扩展。
它将按如下方式使用:
如果需要,您也可以传递自定义宽度。在上面的例子中我选择了默认宽度。
有关我在重构中使用的内容的参考,以下 StackOverflow 链接很有帮助:
Advanced by refactor
substringToIndex 重构
I would like to provide a more Swifty version of what Fonix provided earlier and using Swift 5 syntax. Also I decided to write the functions as an extension of
UILabel
.It'll be used as follows:
Also you can pass a custom width as well if you need to. I opted for the default width in the above example.
For references on what I used in my refactor, the below StackOverflow links were helpful:
Advanced by refactor
substringToIndex refactor
为什么不编写代码来计算字符串的长度并在超出视图时生成其子字符串。或者做任何你想做的事
这是原始但有效的方法
why dont you code to count the length of string and makes its substring if its exceeding the view. or do anything you want
It is raw but effective method