SwiftUI 1.Text介绍和使用
SwiftUI 的 Text
是用于显示静态文本的核心组件,它提供了丰富的样式和布局控制。以下是 Text
的详细介绍和使用示例:
一、基础用法
1. 显示简单文本
Text("Hello, SwiftUI!")
2. 设置字体样式
Text("Hello, SwiftUI!").font(.title) // 系统字体(如 .title, .body, .caption).fontWeight(.bold) // 字重(.light, .medium, .black 等).italic() // 斜体.underline() // 下划线
3. 修改颜色和对齐
Text("Hello, SwiftUI!").foregroundColor(.blue) // 文字颜色.multilineTextAlignment(.center) // 多行对齐方式.frame(width: 200) // 控制布局范围
二、高级功能
1. 多行文本与截断
Text("This is a long text that might need to wrap or truncate.").lineLimit(3) // 最多显示3行.truncationMode(.tail) // 截断位置(.head, .middle, .tail).lineSpacing(10) // 行间距
2. Markdown 支持(iOS 15+)
Text("**Bold Text** *Italic* [Link](https://apple.com)")// 直接渲染 Markdown
3. 本地化字符串
Text("welcome_message", tableName: "Localizable")// 使用 Localizable.strings 中的键值
4. 格式化日期、数字等
Text(Date(), style: .date) // 显示日期(如 "June 23, 2023")
Text(100.0, format: .currency(code: "USD")) // 格式化为 "$100.00"
三、自定义样式
1. 组合不同样式的文本
Text("Hello ")+ Text("SwiftUI").foregroundColor(.red).bold()
2. 使用 AttributedString
(iOS 15+)
var attributedText: AttributedString {var text = AttributedString("Custom Style")text.font = .titletext.foregroundColor = .purplereturn text
}Text(attributedText)
3. 添加阴影和边框
Text("Stylish Text").shadow(color: .gray, radius: 2, x: 1, y: 1).border(.green, width: 1)
四、与其他组件结合
1. 在布局容器中使用
VStack {Text("First Line")Text("Second Line").padding()
}
2. 结合 Image
HStack {Text("Apple Logo")Image(systemName: "applelogo")
}
五、常见问题
-
动态内容更新:
Text
会自动响应绑定的数据变化。@State var count = 0 Text("Count: \(count)") // 当 count 变化时自动更新
-
性能优化:避免在频繁更新的内容中使用复杂样式。
-
自定义字体:
Text("Custom Font").font(.custom("AvenirNext-Regular", size: 20))
六、完整示例
struct ContentView: View {@State private var counter = 0var body: some View {VStack(spacing: 20) {Text("Welcome!").font(.largeTitle).foregroundColor(.indigo)Text("You have \(counter) items").font(.body).foregroundColor(.secondary)Button("Add") { counter += 1 }}}
}
通过灵活组合这些功能,你可以轻松实现从简单标签到复杂富文本的展示需求。