Removing multiple sheets after swiping down the last one swiftui - ios

I currently have two sheets in a row and I want them to be dismissed to the view that called the first sheet once the last sheet is dismissed by the user. I am open to not pulling up views as sheets its just the way I learned how to easily pull up new views.
BookView is what I want to be returned after the PickDefinition sheet view has been dismissed.
BookView pulls up AddWord as a sheet.
AddWord is pulled up as a sheet and then in it PickDefinition is pulled up as a sheet.
After PickDefinition is dismissed I would like for it to go back to the BookView
struct BookView: View {
#ObservedObject var book: Book
#State var addingWord = false
#Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
List(Array(zip(book.words, book.definitions)), id: \.self.0) { (word, definition) in
Text("\(word) - \(definition)")
}
}
.onAppear(perform: {
DB_Manager().openBook(name: book.name, book: self.book)
})
.navigationBarTitle("\(book.name)")
.navigationBarItems(trailing: Button(action: {
self.addingWord = true
}) {
Image(systemName: "plus")
}
).sheet(isPresented: $addingWord) {
AddWord(book: self.book)
}
}
}
struct AddWord: View {
#ObservedObject var book: Book
#StateObject var currentArray = SaveArray()
#State var addingDefinition = false
#State var word = ""
#State var definition = ""
#State var allDefinitions: [String] = []
#Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
Form {
TextField("Word: ", text: $word)
}
.navigationBarTitle("Add word")
.navigationBarItems(trailing: Button("Add") {
if self.word != "" {
book.words.append(self.word)
getDef(self.word, book, currentArray)
addingDefinition = true
}
}).sheet(isPresented: $addingDefinition) {
PickDefinition(definitions: currentArray, book: book, word: self.word)
}
}
}
struct PickDefinition: View {
#ObservedObject var definitions: SaveArray
var book: Book
var word: String
#Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
VStack {
List {
ForEach(0 ..< definitions.currentArray.count) { index in
Button("\(self.definitions.currentArray[index])", action: {
print("hello")
DB_Manager().addWords(name: self.book.name, word: self.word, definition: self.definitions.currentArray[index])
book.definitions.append(self.definitions.currentArray[index])
self.presentationMode.wrappedValue.dismiss()
})
}
}
}
.navigationTitle("Choose")
}
}
}

You need to pass addingWord into the AddWord view, and then into the PickDefinition view, using Binding. When PickDefinition disappears, set the passed property to false to hide the AddWord sheet.
struct BookView: View {
var body: some View {
// ...
.sheet(isPresented: $addingWord) {
AddWord(book: self.book, presentAddingWord: $addingWord)
}
}
}
struct AddWord: View {
#Binding var presentAddingWord: Bool
// ...
var body: some View {
// ...
.sheet(isPresented: $addingDefinition) {
PickDefinition(/* ... */, presentAddingWord: $presentAddingWord)
}
}
}
struct PickDefinition: View {
#Binding var presentAddingWord: Bool
// ...
var body: some View {
// ...
.onDisappear {
presentAddingWord = false
}
}
}

Related

Supply any string value to swiftUI form in different for textfield

I have two view file. I have textfield. I want to supply string value to the textfield from another view
File 1 :- Place where form is created
struct ContentView: View {
#State var subjectLine: String = ""
var body: some View {
form {
Section(header: Text(NSLocalizedString("subjectLine", comment: ""))) {
TextField("SubjectLine", text: $subjectLine
}
}
}
}
File 2 :- Place where I want to provide value to the string and that will show in the textfield UI
struct CalenderView: View {
#Binding var subjectLine: String
var body : some View {
Button(action: {
subjectLine = "Assigned default value"
}, label: {
Text("Fill textfield")
}
}
})
}
}
This is not working. Any other way we can supply value to the textfield in other view file.
As i can understand you have binding in CalenderView
that means you want to navigate there when you navigate update there.
struct ContentView: View {
#State private var subjectLine: String = ""
#State private var showingSheet: Bool = false
var body: some View {
NavigationView {
Form {
Section(header: Text(NSLocalizedString("subjectLine", comment: ""))) {
TextField("SubjectLine", text: $subjectLine)
}
}
.navigationBarItems(trailing: nextButton)
.sheet(isPresented: $showingSheet) {
CalenderView(subjectLine: $subjectLine)
}
}
}
var nextButton: some View {
Button("Next") {
showingSheet.toggle()
}
}
}
CalendarView
struct CalenderView: View {
#Binding var subjectLine: String
#Environment(\.dismiss) private var dismiss
var body: some View {
Button {
subjectLine = "Assigned default value"
dismiss()
} label: {
Text("Fill textfield")
}
}
}

SwiftUI view parameter does not update as expected

I am curious why this .fullScreenCover display of a view does not update properly with a passed-in parameter unless the parameter is using the #Binding property wrapper. Is this a bug or intended behavior? Is this the fact that the view shown by the fullScreenCover is not lazily generated?
import SwiftUI
struct ContentView: View {
#State private var showFullScreen = false
#State private var message = "Initial Message"
var body: some View {
VStack {
Button {
self.message = "new message"
showFullScreen = true
} label: {
Text("Show Full Screen")
}
}.fullScreenCover(isPresented: $showFullScreen) {
TestView(text: message)
}
}
}
struct TestView: View {
var text: String
var body: some View {
Text(text)
}
}
There is a different fullScreenCover for passing in dynamic data, e.g.
import SwiftUI
struct CoverData: Identifiable {
var id: String {
return message
}
let message: String
}
struct FullScreenCoverTestView: View {
#State private var coverData: CoverData?
var body: some View {
VStack {
Button {
coverData = CoverData(message: "new message")
} label: {
Text("Show Full Screen")
}
}
.fullScreenCover(item: $coverData, onDismiss: didDismiss) { item in
TestView(text: item.message)
.onTapGesture {
coverData = nil
}
}
}
func didDismiss() {
// Handle the dismissing action.
}
}
struct TestView: View {
let text: String
var body: some View {
Text(text)
}
}
More info and an example in the docs:
https://developer.apple.com/documentation/SwiftUI/AnyView/fullScreenCover(item:onDismiss:content:)

SwiftUI how to pass data to previous screen on dismiss

I want pass data on dismissing of presentViewController to previous screen. Here I would like to use block to pass data to previous screen as UIKitApp. But I'm not getting idea to pass data. What are the options we have to pass data to back?
struct ContentView: View {
#State var showModel = false
var body: some View {
VStack {
Button(action: {
showModel.toggle()
}, label: {
Text("Show filters")
}).sheet(isPresented: $showModel, content: {
FilterView()
})
}
}
}
struct FilterView: View {
#Environment(\.presentationMode) var presentationMode
var onDismiss: ((_ model: Filter) -> Void)?
var body: some View {
VStack {
Button(action: {
// Pass data from here to ContentView
let filter = Filter(fromDate: "10/07/2021", toDate: "12/07/2021")
onDismiss?(filter)
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Applay Filters")
}).padding()
}.padding()
}
}
struct Filter {
var fromDate: String
var toDate: String
}
You can use #Binding for that (or #StateObject, #ObservedObject, #Environmentobject with #ObservableObject using MVVM Design Pattern)
The code below is an example using #Binding.
Added/Edited Lines
Text("\(filter.fromDate) and \(filter.toDate)") // to see the changed values
#State var filter = Filter(fromDate: "", toDate: "") // in ContentView
#Binding var filter: Filter // in FilterView
FilterView(filter: $filter) // $ used for #Binding parameter
Full Code
struct ContentView: View {
#State var showModel = false
#State var filter = Filter(fromDate: "", toDate: "")
var body: some View {
VStack {
Text("\(filter.fromDate) and \(filter.toDate)")
Button(action: {
showModel.toggle()
}, label: {
Text("Show filters")
}).sheet(isPresented: $showModel, content: {
FilterView(filter: $filter)
})
}
}
}
struct FilterView: View {
#Environment(\.presentationMode) var presentationMode
var onDismiss: ((_ model: Filter) -> Void)?
#Binding var filter: Filter
var body: some View {
VStack {
Button(action: {
// Pass data from here to ContentView
filter = Filter(fromDate: "10/07/2021", toDate: "12/07/2021")
onDismiss?(filter)
presentationMode.wrappedValue.dismiss()
}, label: {
Text("Applay Filters")
}).padding()
}.padding()
}
}
struct Filter {
var fromDate: String
var toDate: String
}

Why my SwiftUI List is not getting updated?

I use a SwiftUI List and pass a String to a different view via a Binding.
But the list get not updated when I went back.
Here is my example:
struct ContentView: View {
#State private var list = ["a", "b", "c"]
#State private var item: String?
#State private var showSheet = false
var body: some View {
List {
ForEach(list.indices) { i in
Button(action: {
item = list[i]
showSheet.toggle()
}) {
Text(list[i])
}
}
}
.sheet(isPresented: $showSheet, content: {
DetailView(input: $item)
})
}
}
And the detail page:
struct DetailView: View {
#Binding var input: String?
var body: some View {
Text(input ?? "")
.onDisappear{
print("changed to changed")
input = "changed"
}
}
}
What I want to achieve is, that on every Item I click, I see the detail page. After that the element should change to "changed". But this does not happen. Why?
You update item but not list, so don't see any result. Here is corrected variant - store selected index and pass binding to list by index.
Tested with Xcode 12.1 / iOS 14.1
struct ContentView: View {
#State private var list = ["a", "b", "c"]
#State private var item: Int?
var body: some View {
List {
ForEach(list.indices) { i in
Button(action: {
item = i
}) {
Text(list[i])
}
}
}
.sheet(item: $item, content: { i in
DetailView(input: $list[i])
})
}
}
extension Int: Identifiable {
public var id: Self { self }
}
struct DetailView: View {
#Binding var input: String
var body: some View {
Text(input)
.onDisappear{
print("changed to changed")
input = "changed"
}
}
}
I recommend you use .sheet(item:content:) instead of .sheet(isPresented:content:)
struct ContentView: View {
#State private var items = ["a", "b", "c"]
#State private var selectedIndex: Int?
var body: some View {
List {
ForEach(items.indices) { index in
Button(action: {
selectedIndex = index
}) {
Text(items[index])
}
}
}
.sheet(item: $selectedIndex) { index in
DetailView(item: $items[index])
}
}
}
struct DetailView: View {
#Binding var item: String
var body: some View {
Text(item)
.onDisappear {
print("changed to changed")
item = "changed"
}
}
}
This will, however, require the selectedIndex to conform to Identifiable.
You can either create an Int extension:
extension Int: Identifiable {
public var id: Int { self }
}
or create a custom struct for your data (and conform to Identifiable).

SwiftUI Picker in a Form doesn't show the selected row

I am trying to have a Picker that shows which option is currently selected.
Try out the following code which correctly selects the right option but the picker does not show which option is selected:
import SwiftUI
struct ContentView: View {
#State var selectedIndex: Int = 0
let strings: [String] = {
var strings: [String] = []
for i in 0..<10 {
strings.append("\(i)")
}
return strings
}()
var body: some View {
NavigationView {
VStack {
Form {
Picker(selection: $selectedIndex,
label: Text("Selected string: \(strings[selectedIndex])")) {
ForEach(0..<strings.count) {
Text(self.strings[$0]).tag($0)
}
}
}
}
.navigationBarTitle("Form Picker",
displayMode: NavigationBarItem.TitleDisplayMode.inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Anyone know what could be wrong? It's observed using Xcode 11.1 and iOS 13.1
I created the simple picker I call "ListPicker" which should fit the bill. I've written it so it works well in a Form; if you need it outside of a Form you will have to tinker with it. If you see any way to improve the code, please add a comment; this is still a learning experience for all of us.
// MARK: - LIST PICKER (PUBLIC)
struct ListPicker<Content: View>: View {
#Binding var selectedItem: Int
var label: () -> Content
var data: [Any]
var selectedLabel: String {
selectedItem >= 0 ? "\(data[selectedItem])" : ""
}
var body: some View {
NavigationLink(destination: ListPickerContent(selectedItem: self.$selectedItem, data: self.data)) {
ListPickerLabel(label: self.label, value: "\(self.selectedLabel)")
}
}
}
// MARK: - INTERNAL
private struct ListPickerLabel<Content: View>: View {
let label: () -> Content
let value: String
var body: some View {
HStack(alignment: .center) {
self.label()
Spacer()
Text(value)
.padding(.leading, 8)
}
}
}
private struct ListPickerContentItem: View {
let label: String
let index: Int
let isSelected: Bool
var body: some View {
HStack {
Text(label)
Spacer()
if isSelected {
Image(systemName: "checkmark")
.foregroundColor(.accentColor)
}
}.background(Color.white) // so the entire row is selectable
}
}
private struct ListPickerContent: View {
#Environment(\.presentationMode) var presentationMode
#Binding var selectedItem: Int
var data: [Any]
var body: some View {
List {
ForEach(0..<data.count) { index in
ListPickerContentItem(label: "\(self.data[index])", index: index, isSelected: index == self.selectedItem).onTapGesture {
self.selectedItem = index
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
}
Then you can use it like this:
#State var selectedCar: Int = 0
let cars = ["Jaguar", "Audi", "BMW", "Land Rover"]
Form {
ListPicker(
selectedItem: self.$selectedCar,
label: {
Text("Cars")
},
data: self.cars
)
}

Resources