3

我如何在列表行上进行自定义叠加,以便在点击时突出显示它。我正在使用NaviagationLink并且我已更改

UITableViewCell.appearance().cellSelectionStyle = .none 

为了不使用默认的灰色选择。

我试图在@State isSelected我的单元格中添加一些,但我不知道如何/何时更改它以获得这种影响。我尝试添加onTapGesture(),但它阻止 NavigationLink,并且不提供开始、结束状态,只是结束。

4

2 回答 2

5

我这样做:

List {
    ForEach(0..<self.contacts.count) { i in
       ZStack {
           NavigationLink(destination: ContactDetails(contact: self.contacts[i])) {
                EmptyView()
           }.opacity(0)

           Button(action: {}) {
                   ContactRow(contact: self.contacts[i])
           }.buttonStyle(ListButtonStyle())
        }.listRowBackground( (i%2 == 0) ? Color("DarkRowBackground") : .white)
           .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
     }
}

并且ButtonStyle

struct ListButtonStyle: ButtonStyle {

    func makeBody(configuration: Self.Configuration) -> some View {

        configuration.label
            .overlay(configuration.isPressed ? Color("Dim").opacity(0.4) : Color.clear)
    }
}
于 2019-11-29T09:55:55.007 回答
4

好的,这是该方法的非常简单的演示。我们的想法是将 NavigationLink 排除在 List 之外并在行点击时手动激活它(它可以在没有导航链接的情况下轻松点击)......其他一切,如动画、效果和高亮类型都取决于您。

import SwiftUI
import UIKit

struct TestCustomCellHighlight: View {
    @State var selection: Int = -1
    @State var highlight = false
    @State var showDetails = false

    init() {
        UITableViewCell.appearance().selectionStyle = .none
    }

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("Details \(self.selection)"), isActive: $showDetails) {
                    EmptyView()
                }
                List(0..<20, id: \.self) { i in
                    HStack {
                        Text("Item \(i)")
                        Spacer()
                    }
                    .padding(.vertical, 6)
                    .background(Color.white) // to be tappable row-wide
                    .overlay(self.highlightView(for: i))
                    .onTapGesture {
                        self.selection = i
                        self.highlight = true

                        // delay link activation to see selection effect
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            self.highlight = false
                            self.showDetails = true
                        }
                    }
                }
            }
        }
    }

    private func highlightView(for index: Int) -> AnyView {
        if self.highlight && self.selection == index {
            return AnyView(Rectangle().inset(by: -5).fill(Color.red.opacity(0.5)))
        } else {
            return AnyView(EmptyView())
        }
    }
}

struct TestCustomCellHighlight_Previews: PreviewProvider {
    static var previews: some View {
        TestCustomCellHighlight()
    }
}
于 2019-11-28T17:26:54.517 回答