一个简单的 SwiftUI 概念验证库,它使用 SwiftUI Text 元素渲染类似 HTML 的语言。
这个项目的目标是测试上述概念验证。目前,解析器和渲染器都有相当多的错误。使用的语言与 HTML 密切相关,熟悉 HTML 的人应该也能轻松理解。字符串被解析成一个由 Tag
结构体组成的抽象语法树。然后将树渲染为 SwiftUI 原生的 Text
视图。
以下标签已实现
largeTitle
/ h1
title
/ h2
headline
/ h3
subheadline
/ h4
body
callout
/ h5
caption
/ h6
footnote
b
i
u
br
font
family (字体)
size (大小)
color (颜色)
family
和 size
属性必须同时存在才能生效color
只能使用十六进制值,例如 #ff0000
和 #ff0000aa
目前尚未实现 h1/h2/h3/h4/h5 等块级元素。只能使用 \n
和 <br/>
添加换行符。
类似 XML 的解析器非常简陋,不遵循任何规范。与 HTML 不同,每个打开的标签都必须关闭 - 这包括 <br/>
。
import SwiftUI
import SwiftUIFormattedText
struct ContentView : View {
@State var string: String = "Type some text here..."
var body: some View {
VStack {
TextField($string)
.lineLimit(nil)
FormattedText(formatted: string)
.padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
<h1>This is a h1</h1><br/>
<largeTitle>This is a largeTitle</largeTitle><br/>
<br/>
<h2>This is a h2</h2><br/>
<title>This is a title</title><br/>
<br/>
<h3>This is a h3</h3><br/>
<headline>This is a headline</headline><br/>
<br/>
<h4>This is a h4</h4><br/>
<subheadline>This is a subheadline</subheadline><br/>
<br/>
<h5>This is a h5</h5><br/>
<callout>This is a callout</callout><br/>
<br/>
<h6>This is a h6</h6><br/>
<caption>This is a caption</caption><br/>
<br/>
<body>The meaning of body is different compared to HTML</body><br/>
<footnote>This is a footnote</footnote><br/>
<i>This text is italic and this is <b>bold.</b></i><br/>
<u>This text should appear underlined.</u><br/>
<font color="#ff0000">This text should appear in red</font><br/>
Text can also wrap multiple lines:<br/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.