带有NavigationLink的SwiftUI列表。如何在点击时更改突出显示颜色?

时间:2020-02-14 22:01:47

标签: list row swiftui highlight swiftui-navigationlink

我有一个带有NavigationLink的列表。当我点击一行时,它会突出显示。与用户界面样式(在info.plist中)相关的颜色可以是深色或浅色。如何改变高光的颜色?我在此处使用“ EpmtyView()”和“ .buttonStyle()”创建了一些决策,但在我的情况下它们不起作用。使用自定义按钮样式时,仅突出显示单元格的内容(例如,文本),而不突出显示单元格本身。我认为,该问题与“ selectionStyle”相关,导致“ UITableViewCell.appearance()。selectionStyle = .none”删除了此突出显示。

struct ContentView: View {
    var myArray = ["one", "two", "three"]

    init() {
         UITableView.appearance().backgroundColor = UIColor.clear
    }

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(self.myArray, id: \.self) { text in
                        NavigationLink(destination: DestinationView()) {
                            MyRow(text: text)
                        }
                        .listRowBackground(Color.black)
                    }
                }.listStyle(GroupedListStyle())
            }.background(Color.black)
        }
    }
}
extension UINavigationController {
    override open func viewDidLoad() {
        super.viewDidLoad()
        let standartAppearance = UINavigationBarAppearance()
        standartAppearance.backgroundColor = UIColor.black
        navigationBar.standardAppearance = standartAppearance
        navigationBar.scrollEdgeAppearance = standartAppearance
        navigationBar.compactAppearance = standartAppearance
    }
}

row highlight

1 个答案:

答案 0 :(得分:0)

这是可行的方法

该想法是禁用标准选择样式,并根据选定的导航链接标记制作可动画的列表行背景视图。

enter image description here

请在下面查看代码的修改部分...

init() {
    UITableView.appearance().backgroundColor = UIColor.clear
    UITableViewCell.appearance().selectionStyle = .none
}

@State private var selection: Int? = nil
var body: some View {
    NavigationView {
        VStack {
            List {
                ForEach(Array(self.myArray.enumerated()), id: \.1.self) { (i, text) in
                    NavigationLink(destination: DestinationView(), tag: i, selection: self.$selection) {
                        MyRow(text: text)
                    }
                    .onTapGesture {
                        withAnimation {
                            self.selection = i
                        }
                    }
                    .listRowBackground(self.selection == i ? Color.yellow : Color.black)
                }
            }.listStyle(GroupedListStyle())
        }.background(Color.black)
    }
}