Why does the #Published value not get triggered in SwiftUI ObservableObject? - ios

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

Related

Odd animation with .matchedGeometryEffect and NavigationView

I'm working on creating a view which uses matchedGeometryEffect, embedded within a NavigationView, and when presenting the second view another NavigationView.
The animation "works" and it matches correctly, however when it toggles from view to view it happens to swing as if unwinding from the navigation stack.
However, if I comment out the NavigationView on the secondary view the matched geometry works correctly.
I am working on iOS 14.0 and above.
Sample code
Model / Mock Data
struct Model: Identifiable {
let id = UUID().uuidString
let icon: String
let title: String
let account: String
let colour: Color
}
let mockItems: [Model] = [
Model(title: "Test title 1", colour: .gray),
Model(title: "Test title 2", colour: .blue),
Model(title: "Test title 3", colour: .purple)
...
]
Card View
struct CardView: View {
let item: Model
var body: some View {
VStack {
Text(item.title)
.font(.title3)
.fontWeight(.heavy)
}
.padding()
.frame(maxWidth: .infinity, minHeight: 100, alignment: .leading)
.background(item.colour)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
Secondary / Detail View
struct DetailView: View {
#Binding var isShowingDetail: Bool
let item: Model
let animation: Namespace.ID
var body: some View {
NavigationView { // <--- comment out here and it works
VStack {
CardView(item: item)
.matchedGeometryEffect(id: item.id, in: animation)
.onTapGesture {
withAnimation { isShowingDetail = false }
}
ScrollView(.vertical, showsIndicators: false) {
Text("Lorem ipsum dolor...")
}
}
.padding(.horizontal)
.navigationBarTitleDisplayMode(.inline)
}
.navigationViewStyle(.stack)
}
}
Primary View
struct ListView: View {
#State private var selectedCard: Model?
#State private var isShowingCard: Bool = false
#Namespace var animation
var body: some View {
ZStack {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
ForEach(mockItems) { item in
CardView(item: item)
.matchedGeometryEffect(id: item.id, in: animation)
.onTapGesture {
withAnimation {
selectedCard = item
isShowingCard = true
}
}
}
}
.navigationTitle("Test title")
}
.padding(.horizontal)
.navigationViewStyle(.stack)
// show detail view
if let selectedCard = selectedCard, isShowingCard {
DetailView(
isShowingDetail: $isShowingCard,
item: selectedCard,
animation: animation
)
}
}
}
}
Video examples
With NavigationView in DetailView
Without NavigationView in DetailView
Ignore the list view still visible
You don't need second NavigationView (actually I don't see links at all, so necessity of the first one is also under question). Anyway we can just change the layout order and put everything into one NavigationView, like below.
Tested with Xcode 13.4 / iOS 15.5
struct ListView: View {
#State private var selectedCard: Model?
#State private var isShowingCard: Bool = false
#Namespace var animation
var body: some View {
NavigationView {
ZStack { // container !!
if let selectedCard = selectedCard, isShowingCard {
DetailView(
isShowingDetail: $isShowingCard,
item: selectedCard,
animation: animation
)
} else {
ScrollView(.vertical, showsIndicators: false) {
ForEach(mockItems) { item in
CardView(item: item)
.matchedGeometryEffect(id: item.id, in: animation)
.onTapGesture {
selectedCard = item
isShowingCard = true
}
}
}
.navigationTitle("Test title")
}
}
.padding(.horizontal)
.navigationViewStyle(.stack)
.animation(.default, value: isShowingCard) // << animated here !!
}
}
}
struct DetailView: View {
#Binding var isShowingDetail: Bool
let item: Model
let animation: Namespace.ID
var body: some View {
VStack {
CardView(item: item)
.matchedGeometryEffect(id: item.id, in: animation)
.onTapGesture {
isShowingDetail = false
}
ScrollView(.vertical, showsIndicators: false) {
Text("Lorem ipsum dolor...")
}
}
.padding(.horizontal)
.navigationBarTitleDisplayMode(.inline)
.navigationViewStyle(.stack)
}
}
Test module is here

Keyboard in a sheet's

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))
}
}

How do you send values to other classes using ObservableObject in SwiftUI

Im trying to create a simple tip Calculator but i am having a problem once a user has added in the information in the app instead of calculating the tip, the function is returning as if there is an issue somewhere.
Im trying to make it so that when a user inputs a number in the text field and selects a percentage the total tip is displayed underneath.
How do i fix this problem?
Ive added a print statement to print the word "returning" and it keeps printing this word so i think the problem is somewhere in the calculateTip function:
This is my Code for my ContentView class:
struct ContentView: View {
//MARK: - PROPERTIES
#ObservedObject public var tipVM = TipViewModel()
//MARK: - FUNCTIONS
private func endEditing() {
hideKeyboard()
}
//MARK: - BODY
var body: some View {
Background {
NavigationView {
ZStack {
VStack {
HStack(spacing: 10) {
Text("Tip Calculator")
.font(.system(.largeTitle, design: .rounded))
.fontWeight(.heavy)
.padding(.leading, 4)
.foregroundColor(.blue)
Spacer()
Button(action: {
// tipVM.clearFields()
}, label: {
Text("Clear")
.font(.system(size: 16, weight: .semibold, design: .rounded))
.padding(.horizontal, 10)
.frame(minWidth: 70, minHeight: 24)
.background(
Capsule().stroke(lineWidth: 2)
)
.foregroundColor(.blue)
}) //: BUTTON
} //: HSTACK
.padding()
Spacer(minLength: 80)
TextField("Enter Amount: ", text: $tipVM.amount)
.padding()
.background(Color.secondary)
.foregroundColor(.white)
.font(.system(.title3, design: .rounded))
Picker(selection: $tipVM.tipPercentage, label: Text("Picker"), content: {
ForEach(0 ..< tipVM.tipChoices.count) { index in
Text("\(self.tipVM.tipChoices[index])%").tag(index)
.font(.system(.body, design: .rounded)).padding()
}.padding()
.background(subtitleColor)
.foregroundColor(.white)
}).onTapGesture(perform: {
tipVM.calculateTip()
})
.pickerStyle(SegmentedPickerStyle())
Text(tipVM.tip == nil ? "£0" : "\(tipVM.tip!)")
.font(.system(.largeTitle, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.blue)
.padding()
} //: VSTACK
} //: ZSTACK
.navigationBarHidden(true)
} //: NAVIGATION VIEW
.navigationViewStyle(StackNavigationViewStyle())
}.onTapGesture {
self.endEditing()
}
.ignoresSafeArea(.keyboard, edges: .all)
} //: BACKGROUND
}
And here is my code for my TipViewModel Class:
import Foundation
import SwiftUI
import Combine
class TipViewModel: ObservableObject {
var amount: String = ""
var tipPercentage: Int = 0
var tip: Double?
let tipChoices = [10,15,20,25,30]
let didChange = PassthroughSubject<TipViewModel, Never>()
func calculateTip() {
guard let amount = Double(amount) else {
print("returning")
return
}
self.tip = amount * (Double(tipPercentage)/100)
self.didChange.send(self)
}
}
I would appreciate any help thanks.
The usual way is to mark the properties with #Published whose changes are going to be monitored. The extra Combine subject is not needed.
And declare tip as non-optional
import Foundation
import SwiftUI
// import Combine
class TipViewModel: ObservableObject {
var amount: String = ""
var tipPercentage: Int = 0
#Published var tip = 0.0
let tipChoices = [10,15,20,25,30]
func calculateTip() {
guard let numAmount = Double(amount) else {
print("returning")
return
}
self.tip = numAmount * (Double(tipPercentage)/100)
}
}
Secondly if the current view struct creates (aka owns) the observable object use always #StateObject rather than #ObservedObject. The latter is for objects which are initialized at higher levels in the view hierarchy and just passed through.
struct ContentView: View {
//MARK: - PROPERTIES
#StatedObject private var tipVM = TipViewModel()
...
Text("£\(tipVM.tip)")

SwiftUI setting individual backgrounds for list Elements that fill the element

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.

Cannot add something to an Array

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 !!
})

Resources