【发布时间】:2019-12-11 20:11:50
【问题描述】:
我有一个执行以下操作的函数:
if let attributedText = attributedText {
size = app_size(for: attributedText, withConstrainedWidth: constrainedWidth)
} else if let text = text {
size = app_size(for: text, withConstrainedWidth: constrainedWidth)
}
各自的app_size 函数返回CGSizes。
尽管在 Playground 中玩弄这个,我意识到无论我在 UILabel 上设置 text 还是 attributedText,attributedText 的值始终存在:
let l = UILabel()
l.text = "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno"
print(l.text)
print(l.attributedText)
// prints:
Optional("this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno")
Optional(this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno{
NSColor = "<UIDynamicSystemColor: 0x600003ead820; name = labelColor>";
NSFont = "<UICTFont: 0x7fa8847014b0> font-family: \".SFUI-Regular\"; font-weight: normal; font-style: normal; font-size: 17.00pt";
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 4, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0 LineBreakStrategy 1";
NSShadow = "NSShadow {0, -1} color = {(null)}";
})
和
let l = UILabel()
l.attributedText = NSAttributedString(string: "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno")
print(l.text)
print(l.attributedText)
// prints
Optional("this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno")
Optional(this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno{
})
那么,如何在 UILabel 上正确检测我是否设置了 text 或 attributedText?谢谢
【问题讨论】: