如何在 UITextView 中设置像块引用一样的文本格式

sar*_*ner 2 uitextview nsattributedstring core-text ios swift

我试图熟悉自己CoreText,并开始制作自己的笔记应用程序。

我将正则表达式与我现在正在输入的文本框结合使用AttributedStrings,并试图从本质上模仿它的功能。StackOverflow

我有所有常见的东西,例如:

大胆的

斜体

标头

emphasis blocks

但我正在努力制作块引用/代码块。

像这样的东西,它会中断自己的行并创建一个框,无论文本有多长,该框都会到达边缘。

And it changes the background color
Run Code Online (Sandbox Code Playgroud)

严格使用 AttributedStrings 是否可以做到这一点?我见过一些注入 HTML / CSS 的旧示例,但我希望我可以使用一些特殊的NSAttributedStringKey组合来完成它。

rob*_*off 5

是的,这是可能的。这是 Swift 3 中的示例 Playground:

import UIKit
import PlaygroundSupport

let richText = NSMutableAttributedString()

let chunk0 = NSAttributedString(string: "But I am struggling to make a block quote / code block.\n\n")
richText.append(chunk0)

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.headIndent = 20
// Note that setting paragraphStyle.firstLineHeadIndent
// doesn't use the background color for the first line's
// indentation. Use a tab stop on the first line instead.
paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: paragraphStyle.headIndent, options: [:])]

let chunk1 = NSAttributedString(string: "\tSomething like this where it breaks to its own line and creates a box that goes to the edge no matter how long the text is.\n", attributes: [
    NSParagraphStyleAttributeName: paragraphStyle,
    NSBackgroundColorAttributeName: UIColor.yellow
])
richText.append(chunk1)

let chunk2 = NSAttributedString(string: "\nIs this even possible to do strictly using AttributedStrings?")
richText.append(chunk2)

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 120, height: 400))
textView.backgroundColor = .white
textView.attributedText = richText
PlaygroundPage.current.liveView = textView
Run Code Online (Sandbox Code Playgroud)

这是输出:

结果

但重要的是要记住,它的功能UITextView(布局和样式)远不如 Web 视图强大。如果你想变得更奇特(就像 stackoverflow 所做的那样,沿着块引用框的左边缘使用较暗的颜色线),你应该只生成 HTML 和 CSS 并使用 Web 视图。