我已经创建了一个普通的UILabel,并希望能够添加行间距到文本,这到UILabel。
虽然当我这样做时,它会影响adjustsFontSizeToFitWidth,并且它不再适合UILabel。
我用过的一些代码:
var userQuestionsAnswer = UILabel(frame: CGRectMake(0, 0, 20, 20))
userQuestionsAnswer.font = UIFont(name: Font.GothamBlack, size: 15)
userQuestionsAnswer.numberOfLines = 0
userQuestionsAnswer.adjustsFontSizeToFitWidth = true
var style = NSMutableParagraphStyle()
style.lineSpacing = view.frame.size.height * 0.021
style.alignment = NSTextAlignment.Center
let attributes = [NSParagraphStyleAttributeName : style]
var answerText = "This is the answer"
self.userQuestionsAnswer.attributedText = NSAttributedString(string: answerText!, attributes:attributes)有没有人能告诉我为什么会这样,以及我是如何解决的?
发布于 2016-04-14 03:57:12
卸下NSMutableParagraphStyle即可正常工作。我不知道为什么,但是这个属性是破坏文本字体大小调整的原因。
发布于 2017-04-24 22:13:46
可能的解决方案是:
在不使用任何语法的情况下,它可能如下所示:
func paragraphStyle(in attrString: NSAttributedString?) -> NSParagraphStyle? {
return attrString?.attribute(NSParagraphStyleAttributeName, at: 0, effectiveRange: nil) as? NSParagraphStyle
}
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
let attributedText = NSMutableAttributedString(string: text, attributes: [
NSFontAttributeName: UIFont.systemFont(ofSize: 20.0),
NSForegroundColorAttributeName: UIColor.orange
])
if let paragraphStyle = paragraphStyle(in: label.attributedText) {
let textRange = NSMakeRange(0, text.characters.count)
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: textRange)
}
label.attributedText = attributedText使用pod 'SwiftyAttributes‘和NSMutableAttributedString扩展:
import SwiftyAttributes
extension NSMutableAttributedString {
func withParagraphStyle(from attrString: NSAttributedString?) -> NSMutableAttributedString {
guard let attrString = attrString, let pStyle = attrString.attribute(.paragraphStyle, at: 0) else {
return self
}
return self.withAttribute(pStyle)
}
}代码将为:
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
label.attributedText = text.withAttributes([
.font(.systemFont(ofSize: 20.0)),
.textColor(.orange)
]).withParagraphStyle(from: label.attributedText)https://stackoverflow.com/questions/29868722
复制相似问题