-
本节课演示如何使用文本视图的扩展方法,对多个不同样式的文本视图进行拼接,从而创建漂亮的富文本。
-
首先设置文字的字体颜色为黄色。
-
同时给文字设置加粗的显示效果。
-
调用文本视图的加号扩展方法,拼接另一个文本视图,该扩展方法可以将两个文本视图进行拼接,并返回一个统一的文本视图。
-
设置第二个文本视图的字体颜色为橙色,并给文字添加删除线的效果。
-
使用扩展方法,拼接第三个指定内容的文本视图。
-
设置文本视图的字体颜色为红色,并给文字添加倾斜的显示效果。
-
使用相同的方式,继续拼接第四个文本视图。
-
最后设置第四个文本视图的字体颜色为紫色,同时给文字添加下划线的显示效果。
本节源码:
//
// ContentView.swift
// Copyright © www.hdjc8.com
//
import SwiftUI
struct myAttributedString : Hashable {
var str: String = ""
var isAns: Bool = false
}
struct ContentView: View {
var attributedstrarray: Array<myAttributedString> = [
myAttributedString(str: "abcdef", isAns: false),
myAttributedString(str: "ans1", isAns: true),
myAttributedString(str: "jklmnopqrstuyz", isAns: false),
myAttributedString(str: "ans2", isAns: true),
]
@State var platforms = ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"]
var body: some View {
GeometryReader { geometry in
self.generateContent(in: geometry)
}
}
private func generateContent(in g: GeometryProxy) -> some View {
var width = CGFloat.zero
var height = CGFloat.zero
return ZStack(alignment: .topLeading) {
ForEach(self.attributedstrarray, id: \.self) { platform in
self.item(for: platform)
.padding([.horizontal, .vertical], 4)
.alignmentGuide(.leading, computeValue: { d in
if (abs(width - d.width) > g.size.width)
{
width = 0
height -= d.height
}
let result = width
if platform == self.platforms.last! {
width = 0 //last item
} else {
width -= d.width
}
return result
})
.alignmentGuide(.top, computeValue: {d in
let result = height
if platform == self.platforms.last! {
height = 0 // last item
}
return result
})
}
}
}
func item(for text: myAttributedString) -> some View {
Text(text)
.padding(.all, 5)
.font(.body)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(5)
}
}
#if DEBUG
struct TestWrappedLayout_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif