strikethrough 是 SwiftUI 中用于为文本添加删除线的修饰符。它通常用于表示文本已被删除、过时或不再有效。例如,在待办事项列表中,已完成的任务可以用删除线标记。
strikethrough 的基本用法#
1. 添加删除线#
import SwiftUI
struct ContentView: View {
var body: some View {
Text("This is a strikethrough text")
.strikethrough() // 添加删除线
}
}运行结果:
文本 “This is a strikethrough text” 会显示一条删除线。
2. 自定义删除线的颜色#
你可以通过 strikethrough(_:color:) 方法自定义删除线的颜色:
Text("This is a strikethrough text")
.strikethrough(true, color: .red) // 添加红色删除线true: 表示启用删除线。color: .red: 设置删除线的颜色为红色。
3. 动态控制删除线#
你可以结合 @State 动态控制是否显示删除线。例如:
struct ContentView: View {
@State private var isStrikethrough: Bool = false
var body: some View {
VStack {
Text("Toggle strikethrough")
.strikethrough(isStrikethrough) // 根据状态动态显示删除线
Button("Toggle") {
isStrikethrough.toggle() // 切换删除线状态
}
}
}
}运行结果:
点击按钮可以切换删除线的显示状态。
strikethrough 的常见使用场景#
1. 待办事项列表#
在待办事项列表中,已完成的任务可以用删除线标记:
struct TodoItem: View {
let task: String
let isCompleted: Bool
var body: some View {
Text(task)
.strikethrough(isCompleted) // 根据完成状态显示删除线
.foregroundColor(isCompleted ? .gray : .black) // 完成的任务变为灰色
}
}
struct ContentView: View {
var body: some View {
VStack {
TodoItem(task: "Buy groceries", isCompleted: true)
TodoItem(task: "Finish homework", isCompleted: false)
}
}
}运行结果:
- “Buy groceries” 会显示删除线并变为灰色。
- “Finish homework” 会正常显示。
2. 价格折扣#
在电商应用中,原价可以用删除线表示,折扣价则正常显示:
struct PriceView: View {
var body: some View {
HStack {
Text("$100")
.strikethrough(true, color: .gray) // 原价显示删除线
Text("$80")
.foregroundColor(.red) // 折扣价显示为红色
}
}
}运行结果:
- 原价 “$100” 会显示删除线。
- 折扣价 “$80” 会显示为红色。
3. 文本编辑#
在文本编辑器中,删除线可以用于标记需要删除的内容:
struct TextEditorView: View {
@State private var text: String = "This is some text to edit."
var body: some View {
VStack {
TextEditor(text: $text)
.frame(height: 100)
Text(text)
.strikethrough(text.contains("edit")) // 如果文本包含 "edit",显示删除线
}
}
}运行结果:
如果文本包含 “edit”,则会显示删除线。
strikethrough 的参数说明#
| 参数 | 描述 |
|---|---|
isActive: Bool | 是否启用删除线。默认为 true。 |
color: Color? | 删除线的颜色。如果为 nil,则使用文本的默认颜色。 |
总结#
什么时候使用 strikethrough?#
- 表示删除或过时:例如待办事项列表中已完成的任务、商品的原价等。
- 文本标记:在文本编辑或注释中,标记需要删除的内容。
- 视觉区分:通过删除线将某些文本与其他文本区分开来。
如何使用 strikethrough?#
- 使用
.strikethrough()为文本添加删除线。 - 使用
.strikethrough(true, color: .red)自定义删除线的颜色。 - 结合
@State动态控制删除线的显示状态。
strikethrough 是一个简单但非常有用的修饰符,能够帮助你更好地表达文本的状态和含义。