Код: Выделить всё
import SwiftUI
class SampleData: Identifiable {
let id = UUID().uuidString
let title: String
init(title: String) {
self.title = title
}
}
struct ContentViewA: View {
@State private var showDropDown: Bool = false
@State private var data: [SampleData] = [SampleData(title: "Mark"), SampleData(title: "John"), SampleData(title: "Paul"), SampleData(title: "Jaime"),
SampleData(title: "Michael"), SampleData(title: "David"), SampleData(title: "Andy"), SampleData(title: "Ryan"),
SampleData(title: "Henry"), SampleData(title: "Chad")]
@State private var selectedData: SampleData?
var body: some View {
NavigationStack {
VStack {
/// This scrollview is needed as my custom view is a bit complex and has other elements that needs to be scrolled.
ScrollView {
Button { self.showDropDown = true } label: {
Text("Tap to open")
}
.frame(width: UIScreen.main.bounds.width/2 - 45.0, height: 45.0)
.padding(8.0)
.font(.headline)
.overlay(dropDownView.offset(y: 55), alignment: .topLeading).zIndex(10)
}
}
}
}
var dropDownView: some View {
ZStack {
if showDropDown {
Spacer()
ScrollViewReader { proxy in
ScrollView(.vertical, showsIndicators: false) {
LazyVStack {
ForEach(Array(self.data.enumerated()), id: \.offset) { (index, element) in
Text("\(index): \(element.title)")
.font(.caption)
.foregroundColor(getSelectedDataColor(element: element))
.padding(8.0)
.onTapGesture {
selectedData = element
self.showDropDown = false
}
}
}
.onAppear {
if let selectedData = selectedData {
withAnimation {
proxy.scrollTo(selectedData.id)
}
}
}
}
}
}
}
.frame(width: UIScreen.main.bounds.width/2, height: UIScreen.main.bounds.height/4)
.shadow(radius: 4)
}
private func getSelectedDataColor(element: SampleData) -> Color {
guard let selectedData = selectedData else { return Color.primary }
return element.title == selectedData.title ? Color.purple : Color.primary
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... -drop-down