swiftui - .listRowBackground() 的问题
问题描述
我有行视图:
struct TestRow: View {
var rowText: String
var body: some View {
HStack {
Text(rowText)
Spacer()
Image(systemName: "heart.circle.fill")
}
.listRowBackground(Color.red)
}
.listRowbackground 工作正常,但如果我添加 contextMenu,背景更改为默认(白色)并且不从 contextMenu 更改:
struct TestRow: View {
@State var rowColor: Color = Color.mint
var rowText: String
var body: some View {
HStack {
Text(rowText)
Spacer()
Image(systemName: "heart.circle.fill")
}
// .background(rowColor) -> this code working with contextMenu
.listRowBackground(rowColor)
.contextMenu {
VStack {
Button {
//action code
rowColor = Color.red
} label: {
MenuButton(colorOrb: "red_circle", buttonText: "High")
}
Button {
//action code
rowColor = .yellow
} label: {
MenuButton(colorOrb: "yellow_circle", buttonText: "Medium")
}
Button {
//action code
rowColor = .green
} label: {
MenuButton(colorOrb: "green_circle", buttonText: "Normal")
}
}
}
}
}
如果我使用 .background(rowColor) 代替 .listRowBackground(rowColor) 代码可以正常工作,但我需要对所有行进行着色,而不仅仅是 HStack。
解决方案
struct Item: Identifiable {
var id: Int
var color: Color
}
struct ContentView2: View {
@State var items: [Item] = [Item(id: 1, color: .red),
Item(id: 2, color: .yellow),
Item(id: 3, color: .blue)]
var body: some View {
VStack {
List {
ForEach($items) { $item in
TestRow(rowColor: $item.color, rowText: "\(item.id)")
.listRowBackground(item.color)
}
}
}
}
}
struct ContentView2_Previews: PreviewProvider {
static var previews: some View {
ContentView2()
}
}
struct TestRow: View {
@Binding var rowColor: Color
let rowText: String
var body: some View {
HStack {
Text(rowText)
Spacer()
Image(systemName: "heart.circle.fill")
}
// .background(rowColor) -> this code working with contextMenu
.contextMenu {
Button {
//action code
rowColor = Color.red
} label: {
Text("red")
}
Button {
//action code
rowColor = .yellow
} label: {
Text("yellow")
}
Button {
//action code
rowColor = .green
} label: {
Text("green")
}
}
}
}
推荐阅读
- javascript - 双重身份验证器 PHP/JS
- php - 如何获取 mongodb 集合迭代器?
- flutter - 使用 file.copy(path) 并获取新文件后,我在该位置获取 previos 文件
- python - 无法跟踪 Scrapy 中的链接
- ruby-on-rails - Activerecord 查询忽略我无法删除的范围的顺序
- django - Django-3.12,招摇问题
- html - CSS聊天消息边框半径怎么做?
- pandas - Pandas - 在数据框中的列之间移动数据
- sql - 在 SQL 中实现在过程的时间进出状态的附加列
- angular - 仅在导航到父页面时加载 Angular 路由