簡體   English   中英

如何在 swiftUI 中找到選定的列表單元格 indexPath

[英]How to find a selected List cell indexPath in swiftUI

我正在處理 swiftUI 列表,但在 swiftUI 列表中略有掙扎。 如何在swift UITableViewDelegate協議 API 中獲取類似於cellForRowAt的選定單元格 indexPath。

我的列表結構是:

struct ContactList: View {
    @ObservedObject var contactRepo = ContactRepository()
    var body: some View {
        NavigationView {
             List(contactRepo.contacts){ contact in
                  ContactCell(data: contact)
              }
             .navigationTitle("Contacts")
        }
    }
}

列表單元結構是:

struct ContactCell: View {
    var contactData: Contact
    var body: some View {
        HStack {
            Image(systemName: "person.fill")
                .data(urlStr: contactData.profileUrl)
                .frame(width: 60, height: 60)
                .border(separatorColor, width: 1)
                .cornerRadius(5)
                .padding(10)
            VStack(alignment: .leading) {
                Text(contactData.name)
                    .font(.system(size: 20, weight: .semibold, design: .default))
                    .foregroundColor(appTextColor)
                Text(contactData.role)
                    .font(.system(size: 17, weight: .thin, design: .default))
                    .foregroundColor(appTextColor)
            }
            Spacer()
        }
    }
}

您應該能夠在contactRepo.contacts數組上使用firstIndex(of:)方法。

let contact: Contact = /* ... */
let index = contactRepo.contacts.firstIndex(of: contact)

如果你想在列表中插入一些東西,你可以修改contactRepo.contacts數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM