i have made an app in SwiftUI where you can create different classes. The app saves this in an array. I have a textfield and a button in the same view as the scrollview that displays the array. This works perfectly fine and I can easily add new classes. Now I made a new view with a text field and a button. This view can be viewed by pressing a button in the nav bar. It uses the exact same function as the other view, but in the other view adding a item to the array works, in this view it doesn't work. I hope you understand my problem and can help me.
Thank You.
This is the file where I store the array:
import Foundation
import SwiftUI
import Combine
struct Class: Identifiable {
var name: String
var id = UUID()
}
class ClassStore: ObservableObject {
#Published var classes = [Class]()
}
This is the view with the button + textfield that works and the scrollview that displays the array:
import SwiftUI
struct ContentView: View {
#State var showNewClass = false
#ObservedObject var classStore = ClassStore()
#State var newClass: String = ""
#State var toDoColor: Color = Color.pink
func addNewClass() {
classStore.classes.append(
Class(name: newClass)
)
newClass = ""
}
var body: some View {
NavigationView {
VStack {
HStack {
TextField("New Todo", text: $newClass)
Image(systemName: "app.fill")
.foregroundColor(Color.pink)
.padding(.horizontal, 3)
Image(systemName: "books.vertical")
.padding(.horizontal, 3)
if newClass == "" {
Text("Add!")
.foregroundColor(Color.gray)
} else {
Button(action: {
addNewClass()
}) {
Text("Add!")
}
}
}.padding()
ScrollView {
ForEach(self.classStore.classes) { name in
Text(name.name)
}
}
.navigationBarTitle(Text("Schulnoten"))
.navigationBarItems(trailing:
Button(action: {
self.showNewClass.toggle()
}) {
Text("New Class")
}
.sheet(isPresented: $showNewClass) {
NewClass(isPresented: $showNewClass)
})
}
}
}
}
And this is the new view I created, the button and the textfield have the exact same code, but somehow this doesn't work:
import SwiftUI
struct NewClass: View {
#Binding var isPresented: Bool
#State var className: String = ""
#ObservedObject var classStore = ClassStore()
func addNewClass() {
classStore.classes.append(
Class(name: className)
)
}
var body: some View {
VStack {
HStack {
Text("New Class")
.font(.title)
.fontWeight(.semibold)
Spacer()
}
TextField("Name of the class", text: $className)
.padding()
.background(Color.gray)
.cornerRadius(5)
.padding(.vertical)
Button(action: {
addNewClass()
self.isPresented.toggle()
}) {
HStack {
Text("Safe")
.foregroundColor(Color.white)
.fontWeight(.bold)
.font(.system(size: 20))
}
.padding()
.frame(width: 380, height: 60)
.background(Color.blue)
.cornerRadius(5)
}
Spacer()
}.padding()
}
}
Sorry if my English is not that good. I'm not a native speaker.
I assume you should pass same class store from parent view into sheet, ie
struct NewClass: View {
#Binding var isPresented: Bool
#State var className: String = ""
#ObservedObject var classStore: ClassStore // << expect external
and in ContentView
.sheet(isPresented: $showNewClass) {
NewClass(isPresented: $showNewClass, classStore: self.classStore) // << here !!
})
Related
I have a basic window with an input field (page 1), on top of it appears a popup window (page 2), inside of which there is also an input fields and buttons, which, when clicked, will bring up a small window with an input field (page 3). If there is no "Done" on the keyboard, the interface functions normally. If you add a "Done" button, it turns out that its color changes from system color blue to gray when moving from page 2 to page 3. Experimenting and wondering why this is so, I found that the toolbar on page 1 is responsible for the color of the button on page 3... If you change the color of the button on the toolbar on page 1 - it will change on the toolbar on page 3, and page 2 will not be affected. Also, adding buttons causes error: "[LayoutConstraints] Unable to simultaneously satisfy constraints." I want to understand why setting the button on the keyboard for Page 1, I also get a button when I type on Page 3? And why is it grayed out and not working? Why if I change the color for the button on Page 1, does it also change for that gray button on Page 3?
A small representative sample:
ContentView
import SwiftUI
struct ContentView: View {
#State private var bloodClucoseLvl: String = ""
#State private var isSheetShown: Bool = false
#FocusState private var focusField: Bool
var body: some View {
NavigationView {
List {
Section("Add your current blood glucose lvl") {
TextField("5,0 mmol/l", text: $bloodClucoseLvl)
.focused($focusField)
}
Section("Add food or drink") {
Button(action:{
isSheetShown.toggle()
}, label:{
HStack{
Text("Add")
Image(systemName: "folder.badge.plus")
}
})
.sheet(isPresented: $isSheetShown) {
addFoodButton()
}
}
}
.navigationTitle("Page 1 - General")
.toolbar{
ToolbarItem(placement: .keyboard) {
HStack {
Spacer()
Button(action: {
focusField = false
}) {
Text("Done")
}
}
}
}
.ignoresSafeArea(.keyboard)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
addFoodButton
import SwiftUI
struct addFoodButton: View {
#State private var selectedFood: String = ""
#State public var addScreen: Bool = false
var body: some View {
ZStack {
NavigationView {
List {
Section("or choose from category"){
NavigationLink(destination: Alcohol(addScreen: $addScreen)){
Text("Alcohol")
}
}
}
.listStyle(.insetGrouped)
.searchable(text: $selectedFood, prompt: "Search by word")
.navigationTitle("Page 2 - Search in DB")
}
if addScreen{
addScreenView(addScreen: $addScreen)
}
}
}
}
struct Alcohol: View {
#State private var searchInsideCategory: String = ""
#Binding var addScreen: Bool
var body: some View {
List {
Button(action: {addScreen.toggle()}){
Text("Light beer")
}
}
.navigationTitle("Page 2 - Choose beer")
.searchable(text: $searchInsideCategory, prompt: "Search inside a category")
}
}
struct addFoodButton_Previews: PreviewProvider {
static var previews: some View {
addFoodButton()
}
}
addScreenView
import SwiftUI
struct addScreenView: View {
#Binding var addScreen: Bool
#State private var gram: String = ""
var body: some View {
ZStack{
Color.black.opacity(0.2).ignoresSafeArea()
VStack(spacing:0){
Text("Page 3 - Add an item")
.bold()
.padding()
Divider()
VStack(){
TextField("gram", text: $gram)
.padding(.leading, 16)
.padding(.trailing, 16)
.keyboardType(.numberPad)
Rectangle()
.frame(height: 1)
.padding(.leading, 16)
.padding(.trailing, 16)
}.padding()
Divider()
HStack(){
Button(action: {
addScreen.toggle()
}){
Text("Cancel").frame(minWidth:0 , maxWidth: .infinity)
}
Divider()
Button(action: {
addScreen.toggle()
}){
Text("Save").frame(minWidth:0 , maxWidth: .infinity)
}
}.frame(height: 50)
}
.background(Color.white.cornerRadius(10))
.padding([.leading, .trailing], 15)
}
}
}
struct addScreenView_Previews: PreviewProvider {
static var previews: some View {
addScreenView(addScreen: .constant(true))
}
}
So I'm trying to make a list where the background of each element is an image that completely fills the element and I'm struggling to get it to completely fill the area.
here's some simple example code showing what I have so far.
struct Event {
var description:String = "description"
var title:String = "Title"
var view:Image
}
struct RowView: View {
#State var event:Event
var body: some View {
VStack {
Text(event.title)
.font(.headline)
Text(event.description)
.font(.subheadline)
}
}
}
struct ContentView: View {
#State var events:[Event] = [Event(view: Image("blue")),Event( view: Image("red")),Event( view: Image("green"))]
#State private var editMode = EditMode.inactive
var body: some View {
NavigationView {
List() {
ForEach(events.indices, id: \.self) { elementID in
NavigationLink(
destination: RowView(event: events[elementID])) {
RowView(event: events[elementID])
}
.background(events[elementID].view)
.clipped()
}
}
.listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
.navigationTitle("Events")
.navigationBarItems(leading: EditButton())
.environment(\.editMode, $editMode)
}
}
}
This is what's produced by the code as you can see there is a border around the background image still.
I don't know what your images are, but seems that should not be important. Here is a demo on replicated code using colors.
Tested with Xcode 12.1 / iOS 14.1
Modified parts (important highlighted in comments)
struct Event {
var description:String = "description"
var title:String = "Title"
var view:Color
}
struct ContentView: View {
#State var events:[Event] = [Event(view: .blue),Event( view: .red),Event( view: .green)]
#State private var editMode = EditMode.inactive
var body: some View {
NavigationView {
List() {
ForEach(events.indices, id: \.self) { elementID in
events[elementID].view.overlay( // << this !!
NavigationLink(
destination: RowView(event: events[elementID])) {
RowView(event: events[elementID])
})
}
.listRowInsets(EdgeInsets()) // << this !!
}
.listStyle(PlainListStyle()) // << and this !!
.navigationTitle("Events")
.navigationBarItems(leading: EditButton())
.environment(\.editMode, $editMode)
}
}
}
This works:
struct RowView: View {
#State var event:Event
var body: some View {
VStack(alignment: .leading) {
Text(event.title)
.font(.headline)
Text(event.description)
.font(.subheadline)
}
.padding(10)
.foregroundColor(.yellow)
}
}
struct ContentView: View {
#State var events:[Event] = [Event(view: Image("blue")),Event( view: Image("red")),Event( view: Image("green"))]
#State private var editMode = EditMode.inactive
var body: some View {
NavigationView {
List() {
ForEach(events.indices, id: \.self) { elementID in
NavigationLink(
destination: RowView(event: events[elementID])) {
RowView(event: events[elementID])
}
.background(events[elementID].view
.resizable()
.aspectRatio(contentMode: .fill)
)
.clipped()
}
.listRowInsets(EdgeInsets())
}
.listStyle(PlainListStyle())
.navigationTitle("Events")
.navigationBarItems(leading: EditButton())
.environment(\.editMode, $editMode)
}
}
}
This is a derivative of Asperi's answer, so you can accept his answer, but this works with images, and no overlay. Tested on Xcode 12.1, IOS 14.1.
Here is an image where I grabbed arbitrary sized images for "red", "green", and "blue" from Goggle. I took the liberty of changing the row text to yellow so it would show up better.
I have an image grid. Each image on tap should push a view on the NavigationView with the image details.
The navigation link works as intended, but when I press the back button it opens the next image and so on until it has cycled all the images. What is going on?
This is the View:
struct ImageGrid: View {
#ObservedObject var part: Part
#State private var showingImagePicker = false
#State private var inputImage: UIImage?
var body: some View {
Button("add images"){
self.showingImagePicker = true
}
LazyVGrid(columns: [GridItem(.adaptive(minimum:100))]){
ForEach(part.images){ image in
ZStack {
Image(uiImage: image.thumb)
.resizable()
.scaledToFit()
NavigationLink (
destination: ImageDetail(image:image),
label: {
EmptyView()
}
).buttonStyle(PlainButtonStyle())
}
}
}
.sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
ImagePicker(image: self.$inputImage)
}
}
// other functions ...
...
}
and this is the detail View
struct ImageDetail: View {
#ObservedObject var image: TrainingImage
var body: some View {
VStack {
Image(uiImage: image.content)
.resizable()
.scaledToFit()
}
}
}
EDIT:
This is a self-contained example isolating the behaviour. It seems to stop working correctly when the grid is inside a form section. Eliminating the form and the section the navigation link works correctly
import SwiftUI
extension String: Identifiable {
public var id:Int {
self.hashValue
}
}
struct ImageDetail: View {
var image: String
var body: some View {
VStack {
Image(uiImage: UIImage(systemName: image)!)
.resizable()
.scaledToFit()
}
}
}
struct ContentView: View {
#State var images:[String] = ["plus", "minus"]
var body: some View {
NavigationView {
Form {
Section {
LazyVGrid(columns: [GridItem(.adaptive(minimum:100))]){
ForEach(images){ image in
NavigationLink (
destination: ImageDetail(image: image),
label: {
Image(uiImage: UIImage(systemName: image)!)
.resizable()
.scaledToFit()
}
).buttonStyle(PlainButtonStyle())
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
It is Form/List feature to auto-detect links in rows, but you have several in row, so the effect. The solution would be to separate cell view and hide link from auto-detection.
Tested with Xcode 12.0 / iOS 14
struct ContentView: View {
#State var images:[String] = ["plus", "minus"]
var body: some View {
NavigationView {
Form {
Section {
LazyVGrid(columns: [GridItem(.adaptive(minimum:100))]){
ForEach(images){
ImageCellView(image: $0)
}
}
}
}
}
}
}
struct ImageCellView: View {
var image: String
#State private var isActive = false
var body: some View {
Image(uiImage: UIImage(systemName: image)!)
.resizable()
.scaledToFit()
.onTapGesture {
self.isActive = true
}
.background(
NavigationLink (
destination: ImageDetail(image: image), isActive: $isActive,
label: {
EmptyView()
}
))
}
}
I have create the below contrived example to demonstrate my problem. In this code I am expecting the TextField to be initialised with "Test Company X" where X is the view depth based on the ObservableObject ViewModel. This is true and works fine for the first view only. Subsequent views do not get the published value on initial appearance. However as you back through the views and the onAppear triggers it does get initialised. Why is the TextField not correctly initialised on the second and subsequent views?
class TestViewModel: ObservableObject {
#Published var companyName: String = ""
func load(_ viewDepth: Int) {
debugPrint("load: \(viewDepth)")
// Mimic a network request to get data
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
debugPrint("publish: \(viewDepth)")
self.companyName = "Test Company \(viewDepth)"
}
}
}
struct TestFormView: View {
var viewDepth: Int
#Binding var companyName: String
#State private var navigateToNextView: Bool = false
var body: some View {
VStack(alignment: .leading, spacing: 3) {
TextField("Company name", text: $companyName)
.padding()
.background(
RoundedRectangle(cornerRadius: 5)
.strokeBorder(Color.primary.opacity(0.5), lineWidth: 3)
)
Button.init("NEXT") {
self.navigateToNextView = true
}
.frame(maxWidth: .infinity)
.foregroundColor(Color.primary)
.padding(10)
.font(Font.system(size: 18,
weight: .semibold,
design: .default))
.background(Color.secondary)
.cornerRadius(Sizes.cornerRadius)
NavigationLink(destination: TestView(viewDepth: viewDepth + 1), isActive: $navigateToNextView) {
EmptyView()
}
.isDetailLink(false)
Spacer()
}
}
}
struct TestView: View {
#ObservedObject var viewModel = TestViewModel()
var viewDepth: Int
var body: some View {
VStack {
TestFormView(viewDepth: viewDepth, companyName: $viewModel.companyName)
}
.onAppear(perform: {
self.viewModel.load(self.viewDepth)
})
.navigationBarTitle("View Depth \(viewDepth)")
.padding()
}
}
struct TestNavigationView: View {
#State private var begin: Bool = false
var body: some View {
NavigationView {
VStack {
if begin {
TestView(viewDepth: 1)
} else {
Button.init("BEGIN") {
self.begin = true
}
.frame(maxWidth: .infinity)
.foregroundColor(Color.primary)
.padding(10)
.font(Font.system(size: 18,
weight: .semibold,
design: .default))
.background(Color.secondary)
.cornerRadius(Sizes.cornerRadius)
}
}
}
}
}
Your model is recreated (due to current nature of NavigationLink)
SwiftUI 2.0
Fix is simple - use specially intended for such purpose StateObject
struct TestView: View {
#StateObject var viewModel = TestViewModel()
// .. other code
I have a SwiftUI app with a basic List/Detail structure. A new item is created from
a modal sheet. When I create a new item and save it I want THAT list item to be
selected. As it is, if no item is selected before an add, no item is selected after
an add. If an item is selected before an add, that same item is selected after the
add.
I'll include code for the ContentView, but this is really the simplest example of
List/Detail.
struct ContentView: View {
#ObservedObject var resortStore = ResortStore()
#State private var addNewResort = false
#State private var coverDeletedDetail = false
#Environment(\.presentationMode) var presentationMode
var body: some View {
List {
ForEach(resortStore.resorts) { resort in
NavigationLink(destination: ResortView(resort: resort)) {
HStack(spacing: 20) {
Image("FlatheadLake1")
//bunch of modifiers
VStack(alignment: .leading, spacing: 10) {
//the cell contents
}
}
}
}
.onDelete { indexSet in
self.removeItems(at: [indexSet.first!])
self.coverDeletedDetail.toggle()
}
if UIDevice.current.userInterfaceIdiom == .pad {
NavigationLink(destination: WelcomeView(), isActive: self.$coverDeletedDetail) {
Text("")
}
}
}//list
.onAppear(perform: self.selectARow)
.navigationBarTitle("Resorts")
.navigationBarItems(leading:
//buttons
}//body
func removeItems(at offsets: IndexSet) {
resortStore.resorts.remove(atOffsets: offsets)
}
func selectARow() {
//nothing that I have tried works here
print("selectARow")
}
}//struct
And again - the add item modal is extremely basic:
struct AddNewResort: View {
//bunch of properties
var body: some View {
VStack {
Text("Add a Resort")
VStack {
TextField("Enter a name", text: $resortName)
//the rest of the fields
}
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 20, leading: 30, bottom: 20, trailing: 30))
Button(action: {
let newResort = Resort(id: UUID(), name: self.resortName, country: self.resortCountry, description: self.resortDescription, imageCredit: "Credit", price: Int(self.resortPriceString) ?? 0, size: Int(self.resortSizeString) ?? 0, snowDepth: 20, elevation: 3000, runs: 40, facilities: ["bar", "garage"])
self.resortStore.resorts.append(newResort)
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Save Trip")
}
.padding(.trailing, 20)
}
}
}
To show the issue - The list with a selection:
The list after a new item created showing the previous selection:
Any guidance would be appreciated. Xcode 11.4
I tried to reconstitute your code as closely as could so that it builds. Here is what I have in the end. We have a list of resorts and when a new resort is saved in the AddNewResort sheet, if we are currently in split view (horizontalSizeClass is regular), we will select the new resort, otherwise just dismiss the sheet.
import SwiftUI
class ResortStore: ObservableObject {
#Published var resorts = [Resort(id: UUID(), name: "Resort 1")]
}
struct ContentView: View {
#ObservedObject var resortStore = ResortStore()
#State private var addingNewResort = false
#State var selectedResortId: UUID? = nil
var navigationLink: NavigationLink<EmptyView, ResortView>? {
guard let selectedResortId = selectedResortId,
let selectedResort = resortStore.resorts.first(where: {$0.id == selectedResortId}) else {
return nil
}
return NavigationLink(
destination: ResortView(resort: selectedResort),
tag: selectedResortId,
selection: $selectedResortId
) {
EmptyView()
}
}
var body: some View {
NavigationView {
ZStack {
navigationLink
List {
ForEach(resortStore.resorts, id: \.self.id) { resort in
Button(action: {
self.selectedResortId = resort.id
}) {
Text(resort.name)
}
.listRowBackground(self.selectedResortId == resort.id ? Color.gray : Color(UIColor.systemBackground))
}
}
}
.navigationBarTitle("Resorts")
.navigationBarItems(trailing: Button("Add Resort") {
self.addingNewResort = true
})
.sheet(isPresented: $addingNewResort) {
AddNewResort(selectedResortId: self.$selectedResortId)
.environmentObject(self.resortStore)
}
WelcomeView()
}
}
}
struct ResortView: View {
let resort: Resort
var body: some View {
Text("Resort View for resort name: \(resort.name).")
}
}
struct AddNewResort: View {
//bunch of properties
#Binding var selectedResortId: UUID?
#State var resortName = ""
#Environment(\.presentationMode) var presentationMode
#Environment(\.horizontalSizeClass) var horizontalSizeClass
#EnvironmentObject var resortStore: ResortStore
var body: some View {
VStack {
Text("Add a Resort")
VStack {
TextField("Enter a name", text: $resortName)
//the rest of the fields
}
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 20, leading: 30, bottom: 20, trailing: 30))
Button(action: {
let newResort = Resort(id: UUID(), name: self.resortName)
self.resortStore.resorts.append(newResort)
self.presentationMode.wrappedValue.dismiss()
if self.horizontalSizeClass == .regular {
self.selectedResortId = newResort.id
}
}) {
Text("Save Trip")
}
.padding(.trailing, 20)
}
}
}
struct WelcomeView: View {
var body: some View {
Text("Welcome View")
}
}
struct Resort {
var id: UUID
var name: String
}
We need to keep track of the selectedResortId
We create an invisible NavigationLink that will programmatically navigate to the selected resort
We make our list row a Button, so that the user can select a resort by tapping on the row
I started writing a series of articles about navigation in SwiftUI List view, there are a lot of points to consider while implementing programmatic navigation.
Here is the one that describes this solution that I'm suggesting: SwiftUI Navigation in List View: Programmatic Navigation. This solution works at the moment on iOS 13.4.1. SwiftUI is changing rapidly, so we have to keep on checking.
And here is my previous article that explains why a more simple solution of adding a NavigationLink to each List row has some problems at the moment SwiftUI Navigation in List View: Exploring Available Options
Let me know if you have questions, I'd be happy to help where I can.