【发布时间】:2017-09-22 07:14:01
【问题描述】:
我有一个标签,我向它添加了一个属性字符串。字符串是,
let nameText = "My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer."`My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer.`
在此文本中,我尝试在文本开头添加*,因此我使用了属性字符串,代码如下所示,
func attributedTextForFeeApplies() -> NSAttributedString {
let attributedText = NSMutableAttributedString(string: "* " + nameText)
attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, attributedText.length))
attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, attributedText.length))
let superScriptString = "* "
attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count))
attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 9), range: NSMakeRange(0, superScriptString.characters.count))
attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, superScriptString.characters.count))
let superscriptAttributedString = attributedText
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = .byTruncatingTail
superscriptAttributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraph, range: NSMakeRange(0, superscriptAttributedString.length))
return superscriptAttributedString
}
我这样给Label设置了约束,
即使我将行数设置为 0 并且没有高度限制,标签也会像这样截断,
但是当我不使用这行代码 attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count)) 时,它可以正常工作,
如果在中间添加*(不删除attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count))),它可以正常工作,但如果我在文本开头使用它就不起作用,
屏幕截图:
如果我增加字体大小,它也可以工作。
我认为NSAttributedString 存在问题,如果不是,我想知道问题所在。谁能帮帮我。
【问题讨论】:
-
因此 let superscriptAttributedString = attributesText let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byTruncatingTail superscriptAttributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraph, range: NSMakeRange(0, superscriptAttributedString.length))您的标签可以放入行数
-
我没听懂你说的(你的标签可以写成行数吗?)。能否请您详细说明。
-
NSMutableParagraphStyle 这意味着您的单行转换为多行,因此如果您想在单行中输入文本,请不要使用 NSMutableParagraphStyle 。
-
删除这一行 let superscriptAttributedString = attributesText let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byTruncatingTail superscriptAttributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraph, range: NSMakeRange(0, superscriptAttributedString.length) ) 并检查您的输出
-
我实施了您的建议,但没有成功。
标签: ios uilabel nsattributedstring