在 SwiftUI 中,Text 是构建用户界面的基础组件,而属性修饰器(Property Wrappers)则是管理文本状态和行为的核心工具。本文将全面解析 Text 相关的所有属性修饰器,并提供详细用法示例。
一、文本内容与格式修饰器
1. 本地化文本:LocalizedStringKey
Text("welcome_message") // 自动使用本地化字符串
Text(verbatim: "Raw Text") // 禁用本地化
使用场景:
多语言应用开发
显示静态文本内容
需要绕过本地化的特殊情况
2. 格式化显示:.formatted()
@State private var price = 19.99
Text(price, format: .currency(code: "USD"))
// 显示:$19.99
Text(Date.now, format: .dateTime.year().month().day())
// 显示:2023-07-19
支持格式类型:
数字:.number、.percent、.currency
日期:.dateTime、.relative、.iso8601
度量单位:.measurement
二、文本样式修饰器
1. 字体设置:.font()
Text("Hello SwiftUI")
.font(.largeTitle) // 系统预设
.font(.system(size: 24, weight: .bold, design: .rounded)) // 自定义
.font(.custom("AvenirNext-Regular", size: 20)) // 自定义字体
常用预设:
.title、.headline、.subheadline
.body、.callout、.footnote
.caption、.caption2
2. 颜色与透明度:.foregroundColor() & .opacity()
@State private var isHighlighted = false
Text("重要通知")
.foregroundColor(isHighlighted ? .red : .primary)
.opacity(isHighlighted ? 1.0 : 0.7)
动态颜色技巧:
// 根据系统模式自动切换
.foregroundColor(Color(uiColor: .systemBackground))
3. 字体样式:.bold() & .italic()
Text("加粗文本").bold()
Text("斜体文本").italic()
Text("下划线文本").underline()
Text("删除线文本").strikethrough()
4. 字符间距:.tracking() & .kerning()
Text("WIDE TEXT")
.tracking(5) // 增加所有字符间距
Text("Professional")
.kerning(-0.5) // 调整特定字符间距
区别:
tracking:等距增加所有间距
kerning:根据字符对智能调整
三、文本布局修饰器
1. 多行对齐:.multilineTextAlignment()
Text("这是一个很长的文本,需要多行显示时会自动换行,并按照指定方式对齐")
.multilineTextAlignment(.center) // 居中对齐
.lineLimit(3) // 最多显示3行
.lineSpacing(8) // 行间距
对齐选项:
.leading:左对齐
.center:居中对齐
.trailing:右对齐
2. 截断模式:.truncationMode()
Text("这是一个非常长的文本,超出显示范围时将被截断")
.lineLimit(1)
.truncationMode(.middle) // 中间截断
截断模式:
.head:开头截断 (…结尾)
.tail:结尾截断 (开头…)
.middle:中间截断 (开头…结尾)
3. 自动缩放:.minimumScaleFactor()
Text("长文本自适应")
.minimumScaleFactor(0.5) // 最小缩放比例
.lineLimit(1)
.frame(width: 100)
四、文本容器修饰器
1. 内边距:.padding()
Text("带内边距的文本")
.padding() // 默认:各方向15pt
.padding(.horizontal, 20) // 水平方向
.padding(.top, 10) // 顶部
.padding([.leading, .trailing], 15) // 组合方向
2. 背景与边框:.background() & .border()
@State private var isActive = false
Text("可交互文本")
.padding(10)
.background(isActive ? Color.blue : Color.gray)
.cornerRadius(8)
.border(Color.black, width: 1)
.onTapGesture {
isActive.toggle()
}
3. 框架限制:.frame()
Text("固定尺寸文本")
.frame(width: 200, height: 100, alignment: .center)
.background(Color.yellow)
Text("灵活尺寸文本")
.frame(minWidth: 50, maxWidth: .infinity)
.background(Color.green)
五、文本动画修饰器
1. 缩放效果:.scaleEffect()
@State private var scale: CGFloat = 1.0
Text("缩放文本")
.scaleEffect(scale)
.onAppear {
withAnimation(.easeInOut.repeatForever()) {
scale = 1.5
}
}
2. 旋转效果:.rotationEffect()
@State private var angle: Angle = .degrees(0)
Text("旋转文本")
.rotationEffect(angle)
.onTapGesture {
withAnimation(.spring()) {
angle += .degrees(45)
}
}
3. 不透明度动画:.opacity()
@State private var showText = false
VStack {
if showText {
Text("淡入淡出文本")
.transition(.opacity)
}
}
.animation(.easeInOut, value: showText)
.onTapGesture {
showText.toggle()
}
六、高级文本特性
1. 富文本组合:+ 运算符
Text("红色文本")
.foregroundColor(.red) +
Text(" + ") +
Text("蓝色文本")
.foregroundColor(.blue)
.bold()
2. 属性字符串:.attributedText()
import SwiftUI
struct AttributedTextView: UIViewRepresentable {
let text: NSAttributedString
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.attributedText = text
}
}
// 使用示例
AttributedTextView(text: NSAttributedString(
string: "富文本示例",
attributes: [
.foregroundColor: UIColor.red,
.font: UIFont.boldSystemFont(ofSize: 20)
]
))
3. 文本选择:.textSelection()
Text("可选择文本(iOS 15+)")
.textSelection(.enabled) // 允许用户选择复制
七、实战案例:动态样式文本组件
struct DynamicStyleText: View {
@State private var isBold = false
@State private var isItalic = false
@State private var fontSize: CGFloat = 16
@State private var textColor = Color.primary
var body: some View {
VStack(spacing: 20) {
Text("可动态调整样式的文本")
.fontWeight(isBold ? .bold : .regular)
.italic(isItalic)
.font(.system(size: fontSize))
.foregroundColor(textColor)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
HStack {
Button("加粗") { isBold.toggle() }
Button("斜体") { isItalic.toggle() }
ColorPicker("颜色", selection: $textColor)
}
Slider(value: $fontSize, in: 12...36, step: 2) {
Text("字体大小: \(Int(fontSize))")
}
}
.padding()
}
}
八、性能优化技巧
1.避免频繁重建:
// 错误做法:每次视图刷新都创建新字符串
@State var counter = 0
Text("计数: \(counter)") // 每次counter变化都会创建新字符串
Text("计数 \(counter)")
// 正确做法
HStack(spacing: 0) {
Text("计数: ")
.font(.title) // 静态部分样式
Text("\(counter)")
.font(.title)
.foregroundColor(.red)
.contentTransition(.numericText()) // 添加数字变化动画
}
2.高效处理长文本:
Text(loremIpsumText)
.lineLimit(5) // 限制行数
.fixedSize(horizontal: false, vertical: true) // 允许垂直扩展
3.使用惰性容器:
ScrollView {
LazyVStack {
ForEach(0..<1000) { index in
Text("条目 \(index)")
.font(.subheadline)
}
}
}
九、跨平台适配技巧
Text("平台特定文本")
#if os(iOS)
.font(.title2)
#elseif os(macOS)
.font(.title3)
#elseif os(watchOS)
.font(.body)
#endif
.padding()
#if os(tvOS)
.focusable()
#endif
总结
SwiftUI 的 Text 组件通过丰富的修饰器提供了强大的文本控制能力:
-
内容修饰器:控制文本内容与格式
-
样式修饰器:调整字体、颜色和样式
-
布局修饰器:管理文本布局与截断
-
容器修饰器:设置背景、边框和内边距
-
动画修饰器:创建动态文本效果
-
高级特性:支持富文本和文本选择
掌握这些修饰器的组合使用,可以创建出既美观又功能丰富的文本界面。建议在开发中:
-
优先使用系统预设样式保持一致性
-
利用属性修饰器实现动态效果
-
注意跨平台适配差异
-
对长文本列表进行性能优化
通过灵活运用这些技术,你的 SwiftUI 文本将具有专业级的视觉效果和用户体验。
1306

被折叠的 条评论
为什么被折叠?



