富文本 (AttributedText)

在 SwiftUI 中使用此视图非常简单,只需 AttributedText(attributedString),与 Text 的简洁性非常相似。文本内容的宽度是受限的(高度会增长),并且是独立的(没有其他依赖项)。

这里有一个例子,展示了一些更精美的富文本以及内容如何

示例

这段简化的代码仅包含用于测试目的的背景颜色和条形

let weirdText: NSAttributedString = {
	let quote = "The quick brown fox jumps over the lazy 🐕."
	let str = NSMutableAttributedString(string: quote)
	str.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 20), range: NSRange(location: 4, length: 5))
	str.addAttribute(.foregroundColor, value: UIColor.brown, range: NSRange(location: 10, length: 5))
	str.addAttribute(.link, value: NSURL(string: "http://apple.com")!, range: NSRange(location: 16, length: 3))
	str.addAttribute(.underlineStyle, value: 1, range: NSRange(location: 16, length: 3))
	str.addAttribute(.baselineOffset, value: 4, range: NSRange(location: 26, length: 4))
	return str
}()

var body: some View {
	VStack {
		//...
		Color.blue.frame(height: 10)
		HStack {
			Color.red.frame(width: 10, height: 10)
			AttributedText(weirdText)
				.background(Color.green.opacity(0.5))
			Color.red.frame(width: 150, height: 10)
		}
		Color.blue.frame(height: 10)
		//...
	}
}

Screenshot

注意事项

该视图内部使用以下“层”:

虽然此代码已在生产环境中使用,但它有一些缺点我想指出:

联系方式

请以 PR 或电子邮件的形式报告任何反馈、错误、想法

omichde - Oliver Michalak - oliver@werk01.de

安装

将其作为 SwiftPM 包嵌入:https://github.com/omichde/AttributedText - 它应该在 iOS 13 及更高版本中工作...

许可证

AttributedText 在 MIT 许可证下可用

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.