将分段样式选择器添加到SwiftUI的NavigationView中

问题描述 投票:0回答:1

问题和标题一样简单。我正在尝试将Picker样式为SegmentedPickerStyleNavigationBar放入SwiftUI。就像本地Phone应用程序的历史记录页面一样。图片在下面

enter image description here

我一直在寻找Google和Github作为示例项目,库或任何教程,但是没有运气。我认为,如果nativa应用程序和WhatsApp例如拥有它,那么它应该是可能的。任何帮助,将不胜感激。

swift swiftui navigationbar picker navigationview
1个回答
1
投票

您可以将Picker直接放入.navigationBarItems中。

enter image description here

我唯一遇到的麻烦是使选择器居中。 (只是为了表明Picker确实可以在导航栏中,我使用框架和Geometry Reader组合了一种骇人听闻的解决方案。您需要找到一种合适的对中解决方案。)

struct ContentView: View {
    @State private var choices = ["All", "Missed"]
    @State private var choice = 0

    @State private var contacts = [("Anna Lisa Moreno", "9:40 AM"), ("Justin Shumaker", "9:35 AM")]

    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                List {
                    ForEach(self.contacts, id: \.self.0) { (contact, time) in
                        ContactView(name: contact, time: time)
                    }
                    .onDelete(perform: self.deleteItems)
                }
                .navigationBarTitle("Recents")
                .navigationBarItems(
                    leading:
                    HStack {
                        Button("Clear") {
                            // do stuff
                        }
                        Picker(selection: self.$choice, label: Text("Pick One")) {
                            ForEach(0 ..< self.choices.count) {
                                Text(self.choices[$0])
                            }
                        }
                        .frame(width: 130)
                        .pickerStyle(SegmentedPickerStyle())
                            .padding(.leading, (geometry.size.width / 2.0) - 130)
                    },
                trailing: EditButton())
            }
        }
    }

    func deleteItems(at offsets: IndexSet) {
        contacts.remove(atOffsets: offsets)
    }

}

struct ContactView: View {
    var name: String
    var time: String

    var body: some View {
        HStack {
            VStack {
                Image(systemName: "phone.fill.arrow.up.right")
                .font(.headline)
                .foregroundColor(.secondary)
                Text("")
            }
            VStack(alignment: .leading) {
                Text(self.name)
                    .font(.headline)
                Text("iPhone")
                    .foregroundColor(.secondary)
            }
            Spacer()
            Text(self.time)
                .foregroundColor(.secondary)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.