SwiftUI nested LazyVStacks in a single ScrollView - swift

I'm trying to build a comment thread. So top level comments can all have nested comments and so can they and so on and so forth. But I'm having issues around scrolling and also sometimes when expanding sections the whole view just jumps around, and can have a giant blank space at the bottom. The code looks like this:
struct ContentView: View {
var body: some View {
VStack {
HStack {
Text("Comments")
.font(.system(size: 34))
.fontWeight(.bold)
Spacer()
}
.padding()
CommentListView(commentIds: [0, 1, 2, 3], nestingLevel: 1)
}
}
}
struct CommentListView: View {
let commentIds: [Int]?
let nestingLevel: Int
var body: some View {
if let commentIds = commentIds {
LazyVStack(alignment: .leading) {
ForEach(commentIds, id: \.self) { id in
CommentItemView(viewModel: CommentItemViewModel(commentId: id), nestingLevel: nestingLevel)
}
}
.applyIf(nestingLevel == 1) {
$0.scrollable()
}
} else {
Spacer()
Text("No comments")
Spacer()
}
}
}
struct CommentItemView: View {
#StateObject var viewModel: CommentItemViewModel
let nestingLevel: Int
#State private var showComments = false
var body: some View {
VStack {
switch viewModel.viewState {
case .error:
Text("Error")
.fontWeight(.thin)
.font(.system(size: 12))
.italic()
case .loading:
Text("Loading")
.fontWeight(.thin)
.font(.system(size: 12))
.italic()
case .complete:
VStack {
Text(viewModel.text)
.padding(.bottom)
.padding(.leading, 20 * CGFloat(nestingLevel))
if let commentIds = viewModel.commentIds {
Button {
withAnimation {
showComments.toggle()
}
} label: {
Text(showComments ? "Hide comments" : "Show comments")
}
if showComments {
CommentListView(commentIds: commentIds, nestingLevel: nestingLevel + 1)
}
}
}
}
}
}
}
class CommentItemViewModel: ObservableObject {
#Published private(set) var text = ""
#Published private(set) var commentIds: [Int]? = [0, 1, 2, 3]
#Published private(set) var viewState: ViewState = .loading
private let commentId: Int
private var viewStateInternal: ViewState = .loading {
willSet {
withAnimation {
viewState = newValue
}
}
}
init(commentId: Int) {
self.commentId = commentId
fetchComment()
}
private func fetchComment() {
viewStateInternal = .complete
text = CommentValue.allCases[commentId].rawValue
}
}
Has anyone got a better way of doing this? I know List can now accept a KeyPath to child object and it can nest that way, but there's so limited design control over List that I didn't want to use it. Also, while this code is an example, the real code will have to load each comment from an API call, so List won't perform as well as LazyVStack in that regard.
Any help appreciated - including a complete overhaul of how to implement this sort of async loading nested view.

Related

SwiftUI onTapGesture on a text navigate to another screen [duplicate]

Is it possible to have both a NavigationView link coexist with a tap gesture (onLongPressGesture)!?
I can not make it work for the life of me...
ScrollView {
ForEach(self.itemStore.items) { p in
NavigationLink(destination: Details(p: p)) {
CardDetector(p: p, position: self.position)
}
}
}
struct CardDetector: View {
var p: ListData
#State var position: CardPosition
#Namespace var namespace
var body: some View {
Group {
switch position {
case .small:
smallcardView(p: p, namespace: namespace)
.padding()
.frame(maxWidth: .infinity)
.frame(height: 120)
.background(BlurView(style: .regular))
.cornerRadius(10)
.padding(.vertical,6)
.onLongPressGesture {
withAnimation {
position = .big
}
}
.padding(.horizontal)
This causes issues with scrolling... which they say the solution is to add a onTapGesture (according to the answer: Longpress and list scrolling) but then the NavigationLink wont work!?
The solution is to separate link with gestures, making link activated programmatically. In such cases actions, gestures, and scrolling do not conflict.
Here is a simplified demo of possible approach. Tested with Xcode 12.4 / iOS 14.4
struct ContentView: View {
var body: some View {
NavigationView {
List(0..<10) {
LinkCard(number: $0 + 1)
}
}
}
}
struct LinkCard: View {
let number: Int
#State private var isActive = false
#State private var isBig = false
var body: some View {
RoundedRectangle(cornerRadius: 12).fill(Color.yellow)
.frame(height: isBig ? 400 : 100)
.overlay(Text("Card \(number)"))
.background(NavigationLink(
destination: Text("Details \(number)"),
isActive: $isActive) {
EmptyView()
})
.onTapGesture {
isActive.toggle() // << activate link !!
}
.onLongPressGesture {
isBig.toggle() // << alterante action !!
}
}
}
It is a complicated project to explain, but I try: for having possibility to direct link to a View not just like a simple String or Text, I defined Content type which conform to View protocol in our Item struc. So you can link any View that you already designed.
For making tap actually be able open the Link we should work on custom Binding.
struct ContentView: View {
#State private var items: [Item] = [Item(stringValue: "Link 0", destination: Text("Destination 0").foregroundColor(Color.red)),
Item(stringValue: "Link 1", destination: Text("Destination 1").foregroundColor(Color.green)),
Item(stringValue: "Link 2", destination: Text("Destination 2").foregroundColor(Color.blue))]
var body: some View {
NavigationView {
Form {
ForEach(items.indices, id: \.self ) { index in
NavigationLink(destination: items[index].destination , isActive: Binding.init(get: { () -> Bool in return items[index].isActive },
set: { (newValue) in items[index].isActive = newValue })) {
Color.white.opacity(0.01)
.overlay(Text(items[index].stringValue), alignment: .leading)
.onTapGesture { items[index].isActive.toggle(); print("TapGesture! on Index:", index.description) }
.onLongPressGesture { print("LongPressGesture! on Index:", index.description) }
}
}
}
}
}
}
struct Item<Content: View>: Identifiable {
let id: UUID = UUID()
var stringValue: String
var isActive: Bool = Bool()
var destination: Content
}

How to setup NavigationLink in SwiftUI sheet to redirect to new view

I am attempting to build a multifaceted openweathermap app. My app is designed to prompt the user to input a city name on a WelcomeView, in order to get weather data for that city. After clicking search, the user is redirected to a sheet with destination: DetailView, which displays weather details about that requested city. My goal is to disable dismissal of the sheet in WelcomeView and instead add a navigationlink to the sheet that redirects to the ContentView. The ContentView in turn is set up to display a list of the user's recent searches (also in the form of navigation links).
My issues are the following:
The navigationLink in the WelcomeView sheet does not work. It appears to be disabled. How can I configure the navigationLink to segue to destination: ContentView() ?
After clicking the navigationLink and redirecting to ContentView, I want to ensure that the city name entered in the WelcomeView textfield is rendered as a list item in the ContentView. For that to work, would it be necessary to set up an action in NavigationLink to call viewModel.fetchWeather(for: cityName)?
Here is my code:
WelcomeView
struct WelcomeView: View {
#StateObject var viewModel = WeatherViewModel()
#State private var cityName = ""
#State private var showingDetail: Bool = false
#State private var linkActive: Bool = true
#State private var acceptedTerms = false
var body: some View {
Section {
HStack {
TextField("Search Weather by City", text: $cityName)
.padding()
.overlay(RoundedRectangle(cornerRadius: 10.0).strokeBorder(Color.gray, style: StrokeStyle(lineWidth: 1.0)))
.padding()
Spacer()
Button(action: {
viewModel.fetchWeather(for: cityName)
cityName = ""
self.showingDetail.toggle()
}) {
HStack {
Image(systemName: "plus")
.font(.title)
}
.padding(15)
.foregroundColor(.white)
.background(Color.green)
.cornerRadius(40)
}
.sheet(isPresented: $showingDetail) {
VStack {
NavigationLink(destination: ContentView()){
Text("Return to Search")
}
ForEach(0..<viewModel.cityNameList.count, id: \.self) { city in
if (city == viewModel.cityNameList.count-1) {
DetailView(detail: viewModel.cityNameList[city])
}
}.interactiveDismissDisabled(!acceptedTerms)
}
}
}.padding()
}
}
}
struct WelcomeView_Previews: PreviewProvider {
static var previews: some View {
WelcomeView()
}
}
ContentView
let coloredToolbarAppearance = UIToolbarAppearance()
struct ContentView: View {
// Whenever something in the viewmodel changes, the content view will know to update the UI related elements
#StateObject var viewModel = WeatherViewModel()
#State private var cityName = ""
#State var showingDetail = false
init() {
// toolbar attributes
coloredToolbarAppearance.configureWithOpaqueBackground()
coloredToolbarAppearance.backgroundColor = .systemGray5
UIToolbar.appearance().standardAppearance = coloredToolbarAppearance
UIToolbar.appearance().scrollEdgeAppearance = coloredToolbarAppearance
}
var body: some View {
NavigationView {
VStack() {
List () {
ForEach(viewModel.cityNameList) { city in
NavigationLink(destination: DetailView(detail: city)) {
HStack {
Text(city.name).font(.system(size: 32))
Spacer()
Text("\(city.main.temp, specifier: "%.0f")°").font(.system(size: 32))
}
}
}.onDelete { index in
self.viewModel.cityNameList.remove(atOffsets: index)
}
}.onAppear() {
viewModel.fetchWeather(for: cityName)
}
}.navigationTitle("Weather")
.toolbar {
ToolbarItem(placement: .bottomBar) {
HStack {
TextField("Enter City Name", text: $cityName)
.frame(minWidth: 100, idealWidth: 150, maxWidth: 240, minHeight: 30, idealHeight: 40, maxHeight: 50, alignment: .leading)
Spacer()
Button(action: {
viewModel.fetchWeather(for: cityName)
cityName = ""
self.showingDetail.toggle()
}) {
HStack {
Image(systemName: "plus")
.font(.title)
}
.padding(15)
.foregroundColor(.white)
.background(Color.green)
.cornerRadius(40)
}.sheet(isPresented: $showingDetail) {
ForEach(0..<viewModel.cityNameList.count, id: \.self) { city in
if (city == viewModel.cityNameList.count-1) {
DetailView(detail: viewModel.cityNameList[city])
}
}
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
DetailView
struct DetailView: View {
var detail: WeatherModel
var body: some View {
VStack(spacing: 20) {
Text(detail.name)
.font(.system(size: 32))
Text("\(detail.main.temp, specifier: "%.0f")°")
.font(.system(size: 44))
Text(detail.firstWeatherInfo())
.font(.system(size: 24))
}
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView(detail: WeatherModel.init())
}
}
ViewModel
class WeatherViewModel: ObservableObject {
#Published var cityNameList = [WeatherModel]()
func fetchWeather(for cityName: String) {
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&units=imperial&appid=<MyAPIKey>") else { return }
let task = URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else { return }
do {
let model = try JSONDecoder().decode(WeatherModel.self, from: data)
DispatchQueue.main.async {
self.cityNameList.append(model)
}
}
catch {
print(error) // <-- you HAVE TO deal with errors here
}
}
task.resume()
}
}
Model
struct WeatherModel: Identifiable, Codable {
let id = UUID()
var name: String = ""
var main: CurrentWeather = CurrentWeather()
var weather: [WeatherInfo] = []
func firstWeatherInfo() -> String {
return weather.count > 0 ? weather[0].description : ""
}
}
struct CurrentWeather: Codable {
var temp: Double = 0.0
}
struct WeatherInfo: Codable {
var description: String = ""
}
DemoApp
#main
struct SwftUIMVVMWeatherDemoApp: App {
var body: some Scene {
WindowGroup {
// ContentView()
WelcomeView()
}
}
}

List scroll freeze on catalyst NavigationView

I've run in to an odd problem with NavigationView on macCatalyst. Here below is a simple app with a sidebar and a detail view. Selecting an item on the sidebar shows a detail view with a scrollable list.
Everything works fine for the first NavigationLink, the detail view displays and is freely scrollable. However, if I select a list item which triggers a link to a second detail view, scrolling starts, then freezes. The app still works, only the detail view scrolling is locked up.
The same code works fine on an iPad without any freeze. If I build for macOS, the NavigationLink in the detail view is non-functional.
Are there any known workarounds ?
This is what it looks like, after clicking on LinkedView, a short scroll then the view freezes. It is still possible to click on the back button or another item on the sidebar, but the list view is blocked.
Here is the code:
ContentView.swift
import SwiftUI
struct ContentView: View {
var names = [NamedItem(name: "One"), NamedItem(name: "Two"), NamedItem(name:"Three")]
var body: some View {
NavigationView {
List() {
ForEach(names.sorted(by: {$0.name < $1.name})) { item in
NavigationLink(destination: DetailListView(item: item)) {
Text(item.name)
}
}
}
.listStyle(SidebarListStyle())
Text("Detail view")
}
}
}
struct NamedItem: Identifiable {
let name: String
let id = UUID()
}
struct DetailListView: View {
var item: NamedItem
let sections = (0...4).map({NamedItem(name: "\($0)")})
var body: some View {
VStack {
List {
Text(item.name)
NavigationLink(destination: DetailListView(item: NamedItem(name: "LinkedView"))) {
listItem(" LinkedView", "Item")
.foregroundColor(Color.blue)
}
ForEach(sections) { section in
sectionDetails(section)
}
}
}
}
let info = (0...12).map({NamedItem(name: "\($0)")})
func sectionDetails(_ section: NamedItem) -> some View {
Section(header: Text("Section \(section.name)")) {
Group {
listItem("ID", "\(section.id)")
}
Text("")
ForEach(info) { ch in
listItem("Item \(ch.name)", "\(ch.id)")
}
}
}
func listItem(_ title: String, _ value: String, tooltip: String? = nil) -> some View {
HStack {
Text(title)
.frame(width: 200, alignment: .leading)
Text(value)
.padding(.leading, 10)
}
}
}
TestListApp.swift
import SwiftUI
#main
struct TestListApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
I had this very same problem with Mac Catalyst app. On real device (iPhone 7 with iOS 14.4.2) there was no problem but with Mac Catalyst (MacBook Pro with Big Sur 11.2.3) the scrolling in the navigation view stuck very randomly as you explained. I figured out that the issue was with Macbook's trackpad and was related to scroll indicators because with external mouse the issue was absent. So the easiest solution to this problem is to hide vertical scroll indicators in navigation view. At least it worked for me. Below is some code from root view 'ContentView' how I did it. It's unfortunate to lose scroll indicators with big data but at least the scrolling works.
import SwiftUI
struct TestView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: NewView()) {
Text("Navigation Link to new view")
}
}
.onAppear {
UITableView.appearance().showsVerticalScrollIndicator = false
}
}
}
}
OK, so I managed to find a workaround, so thought I'd post this for help, until what seems to be a macCatalyst SwiftUI bug is fixed. I have posted a radar for the list freeze problem: FB8994665
The workaround is to use NavigationLink only to the first level of the series of pages which can be navigated (which gives me the sidebar and a toolbar), and from that point onwards use the NavigationStack package to mange links to other pages.
I ran in to a couple of other gotcha's with this arrangement.
Firstly the NavigationView toolbar loses its background when scrolling linked list views (unless the window is defocussed and refocussed), which seems to be another catalyst SwiftUI bug. I solved that by setting the toolbar background colour.
Second gotcha was that under macCatalyst the onTouch view modifier used in NavigationStack's PushView label did not work for most single clicks. It would only trigger consistently for double clicks. I fixed that by using a button to replace the label.
Here is the code, no more list freezes !
import SwiftUI
import NavigationStack
struct ContentView: View {
var names = [NamedItem(name: "One"), NamedItem(name: "Two"), NamedItem(name:"Three")]
#State private var isSelected: UUID? = nil
init() {
// Ensure toolbar is allways opaque
UINavigationBar.appearance().backgroundColor = UIColor.secondarySystemBackground
}
var body: some View {
NavigationView {
List {
ForEach(names.sorted(by: {$0.name < $1.name})) { item in
NavigationLink(destination: DetailStackView(item: item)) {
Text(item.name)
}
}
}
.listStyle(SidebarListStyle())
Text("Detail view")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.toolbar { Spacer() }
}
}
}
struct NamedItem: Identifiable {
let name: String
let id = UUID()
}
// Embed the list view in a NavigationStackView
struct DetailStackView: View {
var item: NamedItem
var body: some View {
NavigationStackView {
DetailListView(item: item)
}
}
}
struct DetailListView: View {
var item: NamedItem
let sections = (0...10).map({NamedItem(name: "\($0)")})
var linked = NamedItem(name: "LinkedView")
// Use a Navigation Stack instead of a NavigationLink
#State private var isSelected: UUID? = nil
#EnvironmentObject private var navigationStack: NavigationStack
var body: some View {
List {
Text(item.name)
PushView(destination: linkedDetailView,
tag: linked.id, selection: $isSelected) {
listLinkedItem(" LinkedView", "Item")
}
ForEach(sections) { section in
if section.name != "0" {
sectionDetails(section)
}
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(item.name)
}
// Ensure that the linked view has a toolbar button to return to this view
var linkedDetailView: some View {
DetailListView(item: linked)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
self.navigationStack.pop()
}, label: {
Image(systemName: "chevron.left")
})
}
}
}
let info = (0...12).map({NamedItem(name: "\($0)")})
func sectionDetails(_ section: NamedItem) -> some View {
Section(header: Text("Section \(section.name)")) {
Group {
listItem("ID", "\(section.id)")
}
Text("")
ForEach(info) { ch in
listItem("Item \(ch.name)", "\(ch.id)")
}
}
}
// Use a button to select the linked view with a single click
func listLinkedItem(_ title: String, _ value: String, tooltip: String? = nil) -> some View {
HStack {
Button(title, action: {
self.isSelected = linked.id
})
.foregroundColor(Color.blue)
Text(value)
.padding(.leading, 10)
}
}
func listItem(_ title: String, _ value: String, tooltip: String? = nil) -> some View {
HStack {
Text(title)
.frame(width: 200, alignment: .leading)
Text(value)
.padding(.leading, 10)
}
}
}
I have continued to experiment with NavigationStack and have made some modifications which will allow it to swap in and out List rows directly. This avoids the problems I was seeing with the NavigationBar background. The navigation bar is setup at the level above the NavigationStackView and changes to the title are passed via a PreferenceKey. The back button on the navigation bar hides if the stack is empty.
The following code makes use of PR#44 of swiftui-navigation-stack
import SwiftUI
struct ContentView: View {
var names = [NamedItem(name: "One"), NamedItem(name: "Two"), NamedItem(name:"Three")]
#State private var isSelected: UUID? = nil
var body: some View {
NavigationView {
List {
ForEach(names.sorted(by: {$0.name < $1.name})) { item in
NavigationLink(destination: DetailStackView(item: item)) {
Text(item.name)
}
}
}
.listStyle(SidebarListStyle())
Text("Detail view")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.toolbar { Spacer() }
}
}
}
struct NamedItem: Identifiable {
let name: String
let depth: Int
let id = UUID()
init(name:String, depth: Int = 0) {
self.name = name
self.depth = depth
}
var linked: NamedItem {
return NamedItem(name: "Linked \(depth+1)", depth:depth+1)
}
}
// Preference Key to send title back down to DetailStackView
struct ListTitleKey: PreferenceKey {
static var defaultValue: String = ""
static func reduce(value: inout String, nextValue: () -> String) {
value = nextValue()
}
}
extension View {
func listTitle(_ title: String) -> some View {
self.preference(key: ListTitleKey.self, value: title)
}
}
// Embed the list view in a NavigationStackView
struct DetailStackView: View {
var item: NamedItem
#ObservedObject var navigationStack = NavigationStack()
#State var toolbarTitle: String = ""
var body: some View {
List {
NavigationStackView(noGroup: true, navigationStack: navigationStack) {
DetailListView(item: item, linked: item.linked)
.listTitle(item.name)
}
}
.listStyle(PlainListStyle())
.animation(nil)
// Updated title
.onPreferenceChange(ListTitleKey.self) { value in
toolbarTitle = value
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("\(toolbarTitle) \(self.navigationStack.depth)")
.toolbar(content: {
ToolbarItem(id: "BackB", placement: .navigationBarLeading, showsByDefault: self.navigationStack.depth > 0) {
Button(action: {
self.navigationStack.pop()
}, label: {
Image(systemName: "chevron.left")
})
.opacity(self.navigationStack.depth > 0 ? 1.0 : 0.0)
}
})
}
}
struct DetailListView: View {
var item: NamedItem
var linked: NamedItem
let sections = (0...10).map({NamedItem(name: "\($0)")})
// Use a Navigation Stack instead of a NavigationLink
#State private var isSelected: UUID? = nil
#EnvironmentObject private var navigationStack: NavigationStack
var body: some View {
Text(item.name)
PushView(destination: linkedDetailView,
tag: linked.id, selection: $isSelected) {
listLinkedItem(" LinkedView", "Item")
}
ForEach(sections) { section in
if section.name != "0" {
sectionDetails(section)
}
}
}
// Ensure that the linked view has a toolbar button to return to this view
var linkedDetailView: some View {
DetailListView(item: linked, linked: linked.linked)
.listTitle(linked.name)
}
let info = (0...12).map({NamedItem(name: "\($0)")})
func sectionDetails(_ section: NamedItem) -> some View {
Section(header: Text("Section \(section.name)")) {
Group {
listItem("ID", "\(section.id)")
}
Text("")
ForEach(info) { ch in
listItem("Item \(ch.name)", "\(ch.id)")
}
}
}
func buttonAction() {
self.isSelected = linked.id
}
// Use a button to select the linked view with a single click
func listLinkedItem(_ title: String, _ value: String, tooltip: String? = nil) -> some View {
HStack {
Button(title, action: buttonAction)
.foregroundColor(Color.blue)
Text(value)
.padding(.leading, 10)
}
}
func listItem(_ title: String, _ value: String, tooltip: String? = nil) -> some View {
HStack {
Text(title)
.frame(width: 200, alignment: .leading)
Text(value)
.padding(.leading, 10)
}
}
}

SwiftUI picker separate texts for selected item and selection view

I have a Picker embedded in a Form inside a NavigationView. I'd like to have a separate text for the chosen item in the main View and a more detailed descriptions when choosing items in the picker View.
This is what I tried so far:
struct Item {
let abbr: String
let desc: String
}
struct ContentView: View {
#State private var selectedIndex = 0
let items: [Item] = [
Item(abbr: "AA", desc: "aaaaa"),
Item(abbr: "BB", desc: "bbbbb"),
Item(abbr: "CC", desc: "ccccc"),
]
var body: some View {
NavigationView {
Form {
picker
}
}
}
var picker: some View {
Picker(selection: $selectedIndex, label: Text("Chosen item")) {
ForEach(0..<items.count) { index in
Group {
if self.selectedIndex == index {
Text(self.items[index].abbr)
} else {
Text(self.items[index].desc)
}
}
.tag(index)
}
.id(UUID())
}
}
}
Current solution
This is the picker in the main view:
And this is the selection view:
The problem is that with this solution in the selection view there is "BB" instead of "bbbbb".
This occurs because the "BB" text in both screens is produced by the very same Text view.
Expected result
The picker in the main view:
And in the selection view:
Is it possible in SwiftUI to have separate texts (views) for both screens?
Possible solution without a Picker
As mention in my comment, there is not yet a solution for a native implementation with the SwiftUI Picker. Instead, you can do it with SwiftUI Elements especially with a NavigationLink. Here is a sample code:
struct Item {
let abbr: String
let desc: String
}
struct ContentView: View {
#State private var selectedIndex = 0
let items: [Item] = [
Item(abbr: "AA", desc: "aaaaa"),
Item(abbr: "BB", desc: "bbbbb"),
Item(abbr: "CC", desc: "ccccc"),
]
var body: some View {
NavigationView {
Form {
NavigationLink(destination: (
DetailSelectionView(items: items, selectedItem: $selectedIndex)
), label: {
HStack {
Text("Chosen item")
Spacer()
Text(self.items[selectedIndex].abbr).foregroundColor(Color.gray)
}
})
}
}
}
}
struct DetailSelectionView: View {
var items: [Item]
#Binding var selectedItem: Int
var body: some View {
Form {
ForEach(0..<items.count) { index in
HStack {
Text(self.items[index].desc)
Spacer()
if self.selectedItem == index {
Image(systemName: "checkmark").foregroundColor(Color.blue)
}
}
.onTapGesture {
self.selectedItem = index
}
}
}
}
}
If there are any improvements feel free to edit the code snippet.
Expanding on JonasDeichelmann's answer I created my own picker:
struct CustomPicker<Item>: View where Item: Hashable {
#State var isLinkActive = false
#Binding var selection: Int
let title: String
let items: [Item]
let shortText: KeyPath<Item, String>
let longText: KeyPath<Item, String>
var body: some View {
NavigationLink(destination: selectionView, isActive: $isLinkActive, label: {
HStack {
Text(title)
Spacer()
Text(items[selection][keyPath: shortText])
.foregroundColor(Color.gray)
}
})
}
var selectionView: some View {
Form {
ForEach(0 ..< items.count) { index in
Button(action: {
self.selection = index
self.isLinkActive = false
}) {
HStack {
Text(self.items[index][keyPath: self.longText])
Spacer()
if self.selection == index {
Image(systemName: "checkmark")
.foregroundColor(Color.blue)
}
}
.contentShape(Rectangle())
.foregroundColor(.primary)
}
}
}
}
}
Then we have to make Item conform to Hashable:
struct Item: Hashable { ... }
And we can use it like this:
struct ContentView: View {
#State private var selectedIndex = 0
let items: [Item] = [
Item(abbr: "AA", desc: "aaaaa"),
Item(abbr: "BB", desc: "bbbbb"),
Item(abbr: "CC", desc: "ccccc"),
]
var body: some View {
NavigationView {
Form {
CustomPicker(selection: $selectedIndex, title: "Item", items: items,
shortText: \Item.abbr, longText: \Item.desc)
}
}
}
}
Note: Currently the picker's layout cannot be changed. If needed it can be made more generic using eg. #ViewBuilder.
I've had another try at a custom split picker.
Implementation
First, we need a struct as we'll use different items for selection, main screen and picker screen.
public struct PickerItem<
Selection: Hashable & LosslessStringConvertible,
Short: Hashable & LosslessStringConvertible,
Long: Hashable & LosslessStringConvertible
>: Hashable {
public let selection: Selection
public let short: Short
public let long: Long
public init(selection: Selection, short: Short, long: Long) {
self.selection = selection
self.short = short
self.long = long
}
}
Then, we create a custom view with an inner NavigationLink to simulate the behaviour of a Picker:
public struct SplitPicker<
Label: View,
Selection: Hashable & LosslessStringConvertible,
ShortValue: Hashable & LosslessStringConvertible,
LongValue: Hashable & LosslessStringConvertible
>: View {
public typealias Item = PickerItem<Selection, ShortValue, LongValue>
#State private var isLinkActive = false
#Binding private var selection: Selection
private let items: [Item]
private var showMultiLabels: Bool
private let label: () -> Label
public init(
selection: Binding<Selection>,
items: [Item],
showMultiLabels: Bool = false,
label: #escaping () -> Label
) {
self._selection = selection
self.items = items
self.showMultiLabels = showMultiLabels
self.label = label
}
public var body: some View {
NavigationLink(destination: selectionView, isActive: $isLinkActive) {
HStack {
label()
Spacer()
if let selectedItem = selectedItem {
Text(String(selectedItem.short))
.foregroundColor(Color.secondary)
}
}
}
}
}
private extension SplitPicker {
var selectedItem: Item? {
items.first { selection == $0.selection }
}
}
private extension SplitPicker {
var selectionView: some View {
Form {
ForEach(items, id: \.self) { item in
itemView(item: item)
}
}
}
}
private extension SplitPicker {
func itemView(item: Item) -> some View {
Button(action: {
selection = item.selection
isLinkActive = false
}) {
HStack {
if showMultiLabels {
itemMultiLabelView(item: item)
} else {
itemLabelView(item: item)
}
Spacer()
if item == selectedItem {
Image(systemName: "checkmark")
.font(Font.body.weight(.semibold))
.foregroundColor(.accentColor)
}
}
.contentShape(Rectangle())
}
}
}
private extension SplitPicker {
func itemLabelView(item: Item) -> some View {
HStack {
Text(String(item.long))
.foregroundColor(.primary)
Spacer()
}
}
}
private extension SplitPicker {
func itemMultiLabelView(item: Item) -> some View {
HStack {
HStack {
Text(String(item.short))
.foregroundColor(.primary)
Spacer()
}
.frame(maxWidth: 50)
Text(String(item.long))
.font(.subheadline)
.foregroundColor(.secondary)
}
}
}
Demo
struct ContentView: View {
#State private var selection = 2
let items = (1...5)
.map {
PickerItem(
selection: $0,
short: String($0),
long: "Long text of: \($0)"
)
}
var body: some View {
NavigationView {
Form {
Text("Selected index: \(selection)")
SplitPicker(selection: $selection, items: items) {
Text("Split picker")
}
}
}
}
}

persistent value in a picker changing views in SwiftUI

I don't understand how implementing in SwiftUI a simple picker showing a list of values that retain the selected value switching between different views. I'm able to use the selected value to update the Model via Combine framework by the way.
here's the code, but the onAppear{}/onDisappear{} doesn't work as expected:
struct CompanyView: View {
#ObservedObject var dataManager: DataManager = DataManager.shared
#State var selTipoAzienda = 0
var body: some View {
VStack {
companyPhoto
Text("Company view")
Form {
Picker(selection: $selTipoAzienda, label: Text("Tipo Azienda")) {
ForEach(0 ..< self.dataManager.company.tipoAziendaList.count) {
Text(self.dataManager.company.tipoAziendaList[$0])
}
}
}
Button(action: {self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda]) }) {
Image(systemName: "info.circle.fill")
.font(Font.system(size: 28))
.padding(.horizontal, 16)
}
}
// .onAppear{
// self.selTipoAzienda = self.dataManager.company.tipoAziendaList.firstIndex(of: self.dataManager.company.tipoAzienda) ?? 0
// }
// .onDisappear{
// self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda])
// }
}
I think binding and didSet would be the answer but I don't know how they have to be implemented
The provided code is not compilable/testable, so below just shows an approach (see also comments inline)
struct CompanyView: View {
#ObservedObject var dataManager: DataManager = DataManager.shared
#State var selTipoAzienda: Int
init() {
// set up initial value from persistent data manager
_selTipoAzienda = State(initialValue: self.dataManager.company.tipoAziendaList.firstIndex(of: self.dataManager.company.tipoAzienda) ?? 0)
}
var body: some View {
// inline proxy binding to intercept Picker changes
let boundSelTipoAzienda = Binding(get: { self.selTipoAzienda }, set: {
self.selTipoAzienda = $0
// store selected value into data manager
self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[$0])
})
return VStack {
companyPhoto
Text("Company view")
Form {
Picker(selection: boundSelTipoAzienda, label: Text("Tipo Azienda")) {
ForEach(0 ..< self.dataManager.company.tipoAziendaList.count) {
Text(self.dataManager.company.tipoAziendaList[$0])
}
}
}
Button(action: {self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda]) }) {
Image(systemName: "info.circle.fill")
.font(Font.system(size: 28))
.padding(.horizontal, 16)
}
}
}
}