SwiftUI:点击时更改列表行突出显示颜色 [英] SwiftUI: Change List row Highlight colour when tapped

查看:62
本文介绍了SwiftUI:点击时更改列表行突出显示颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击列表行时的默认颜色为灰色.

The default colour of a list row when tapped is grey.

我知道如何使用 .listRowBackground 更改背景颜色,但随后它会更改为整个列表.

I know how to change background colour using .listRowBackground, but then it changes to the whole list.

如何在点击时更改为自定义颜色,以便只有被点击的行保持红色?

How can I change to a custom colour when tapped, so ONLY the tapped row stays red?

import SwiftUI

struct ExampleView: View {
    @State private var fruits = ["Apple", "Banana", "Grapes", "Peach"]

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                }
                .listRowBackground(Color.red)

            }


        }
    }


}

struct ExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleView()
    }
}

推荐答案

首先,您需要在行上使用 .ListRowBackground 修饰符而不是整个列表,然后使用它有条件地设置每一行的行背景颜色.如果将点击行的 ID 保存在 @State 变量中,则可以根据选择状态将行设置为红色或默认颜色.代码如下:

First, you want the .ListRowBackground modifier on the row not the whole list and then use it to conditionally set the row background color on each row. If you save the tapped row's ID in a @State var, you can set the row to red or the default color based on selection state. Here's the code:

import SwiftUI

struct ContentView: View {
    @State private var fruits = ["Apple", "Banana", "Grapes", "Peach"]
    @State private var selectedFruit: String?

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                        .onTapGesture {
                            self.selectedFruit = fruit
                    }
                    .listRowBackground(self.selectedFruit == fruit ? Color.red : Color(UIColor.systemGroupedBackground))
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这篇关于SwiftUI:点击时更改列表行突出显示颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆