ios 如何为 NSAttributedString 中的行添加间距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21370495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add spacing to lines in NSAttributedString
提问by James Campbell
I am making an app that formats screenplays, I am using a NSAttributedString to format the text entered into a UITextView, but some of the lines are too close together.
我正在制作一个格式化剧本的应用程序,我正在使用 NSAttributedString 来格式化输入到 UITextView 中的文本,但有些行太靠近了。
I was wondering if anyone could provide a code example or a tip on how to alter the margin between these lines so there is more space between them.
我想知道是否有人可以提供有关如何更改这些行之间的边距以便它们之间有更多空间的代码示例或提示。
Below is an image of another desktop screenwriting program that demonstrates what I mean, notice how there is a bit of space before each bit where it says "DOROTHY".
下面是另一个桌面编剧程序的图像,它展示了我的意思,注意在每个写着“DOROTHY”的位之前有一点空间。
回答by Joe Smith
The following sample code uses paragraph style to adjust spacing between paragraphs of a text.
以下示例代码使用段落样式来调整文本段落之间的间距。
UIFont *font = [UIFont fontWithName:fontName size:fontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight;
NSDictionary *attributes = @{NSFontAttributeName:font,
NSForegroundColorAttributeName:[UIColor whiteColor],
NSBackgroundColorAttributeName:[UIColor clearColor],
NSParagraphStyleAttributeName:paragraphStyle,
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
To selectively adjust spacing for certain paragraphs, apply the paragraph style to only those paragraphs.
要有选择地调整某些段落的间距,请将段落样式仅应用于这些段落。
Hope this helps.
希望这可以帮助。
回答by Nathaniel
Great answer @Joe Smith
很好的答案@Joe Smith
In case anyone would like to see what this looks like in Swift 2.*:
如果有人想在 Swift 2.* 中看到它的样子:
let font = UIFont(name: String, size: CGFloat)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight
let attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle]
let attributedText = NSAttributedString(string: String, attributes: attributes)
self.textView.attributedText = attributedText
回答by enigma
Here is Swift 4.* version:
这是 Swift 4.* 版本:
let string =
"""
A multiline
string here
"""
let font = UIFont(name: "Avenir-Roman", size: 17.0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 0.25 * (font?.lineHeight)!
let attributes = [NSAttributedStringKey.font: font as Any, NSAttributedStringKey.paragraphStyle: paragraphStyle]
let attrText = NSAttributedString(string: string, attributes: attributes)
self.textView.attributedText = attrText