I'm using a ForEach to parse a list of models and create a view for each of them, Each view contains a Button and a Text, the Button toggles a visibility state which should hide the text and change the Button's title (Invisible/Visible).
struct ContentView: View {
var colors: [MyColor] = [MyColor(val: "Blue"), MyColor(val: "Yellow"), MyColor(val: "Red")]
var body: some View {
ForEach(colors, id: \.uuid) { color in
ButtonColorView(color: color.val)
}
}
}
struct ButtonColorView: View {
var color: String
#State var visible = true
var body: some View {
if visible {
return AnyView( HStack {
Button("Invisible") {
self.visible.toggle()
}
Text(color)
})
} else {
return AnyView(
Button("Visible") {
self.visible.toggle()
}
)
}
}
}
class MyColor: Identifiable {
let uuid = UUID()
let val: String
init(val: String) {
self.val = val
}
}
Unfortunately it's not working, the views inside the ForEach do not change when the Button is pressed. I replaced the Foreach with ButtonColorView(color: colors[0].val) and it seems to work, so I'd say the problem is at ForEach.
I also tried breakpoints in ButtonColorView and it seems the view is called when the Button is triggered returning the right view, anyways the view does not update on screen.
So, am I using the ForEach in a wrong way ?
This problem occurs in a more complex app, but I tried to extract it in this small example. To summarize it: I need ButtonColorView to return different Views depending of its state (visibility in this case)
PS: I'm using Xcode 11 Beta 6
You are using ForEach correctly. I think it's the if statement within ButtonColorView's body that's causing problems. Try this:
struct ButtonColorView: View {
var color: String
#State var visible = true
var body: some View {
HStack {
Button(visible ? "Invisible" : "Visible") {
self.visible.toggle()
}
if visible {
Text(color)
}
}
}
}
You can also try something like this:
struct ButtonColorView: View {
var color: String
#State var visible = true
var body: some View {
HStack {
if visible {
HStack {
Button("Invisible") {
self.visible.toggle()
}
Text(color)
}
} else {
Button("Visible") {
self.visible.toggle()
}
}
}
}
}
Related
Description
I've got simple Combat model which stores name and list of actors. When I delete the Combat from List using onDelete it looks like it's working. It removes the Combat from Realm (checked with RealmStudio) and updates the view. However, if view gets redrawn (for instance, when switching Apps), the "old" data is loaded again (the very first loaded on app initialization), so all deleted rows are back again. Of course, removing them again crashes the app, because they are not present in #ObservedResults combats anymore. Restarting the app fixes the issue, because new data is loaded to #ObservedResults combats and to List, but then again, when I removed something it will be back on review draw...
What I discovered is that removing .sheet() fixes the issue! (EDIT: clarification; it doesn't matter what's inside of the sheet, it may be even empty) The view is updated correctly on redraw! The Sheet is used to display form to add new Combat (nether to say that adding new combats or editing them does not update the view as well, but let's focus on deletion). I have no idea what adding sheet() changes in behaviour of the List and "listening" to #ObservedResults combats.
As a test I used simple array of Combat classes and everything worked. So it points me to issue with #ObservedResults.
I was using the Alert before and all changes to #ObservedResults combats were seen at glance. Now I wanted to replace Alert with Sheet and… That happened.
Also, I have subview where I have almost identical code for actor and there everything works, however I use #ObservedRealmObject var combat: Combat there, and I pass the combat #ObservedResults combats, like so:
NavigationLink(destination: CombatView(combat: combat)) { Text(combat.name) }
I removed unecessary code from below examples to keep it at minimum.
Model
The Combat model:
class Combat: Object, ObjectKeyIdentifiable {
#objc dynamic var id: String = UUID().uuidString
#objc dynamic var name: String = ""
var actors = List<Actor>()
}
Actual View Code (broken using Sheet)
#ObservedResults(
Combat.self,
sortDescriptor: SortDescriptor( keyPath: "name", ascending: true)
) var combats
struct CombatsListView: View {
#ObservedResults(
Combat.self,
sortDescriptor: SortDescriptor( keyPath: "name", ascending: true)
) var combats
var body: some View {
List {
ForEach(combats) { combat in
Text(combat.name)
}.onDelete(perform: $combats.remove)
}
.sheet(isPresented: $showAddCombat) {
AddCombatView( showAddCombat: $showAddCombat)
}
}
}
Old View Code (works using Alert)
struct CombatsListView: View {
#ObservedResults(
Combat.self,
sortDescriptor: SortDescriptor( keyPath: "name", ascending: true)
) var combats
#State private var showAddCombat = false
#State private var addCombatNewName = ""
var body: some View {
List(combats) { combat in
Text(combat.name)
.onDelete(perform: $combats.remove)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
showAlert = true
}) {
Image(systemName: "plus" )
.font(.title)
Text("New Combat")
}.alert("New Combat", isPresented: $showAlert) {
TextField("write name", text: $addCombatNewName)
Button("Close", role: .cancel) {
addCombatNewName = ""
}
Button("Add") {
addNewCombat(name: addCombatNewName)
addCombatNewName = ""
}
}
}
}
}
private func addNewCombat(name: String) {
let newCombat = Combat()
newCombat.name = name
do {
try self.realm.write {
realm.add(newCombat)
}
} catch {
fatalError("Error: \(error)")
}
}
}
EDITED
I just found some new behaviour. I made a new simple view which lists elements of Collection list and you can delete or add new Collection. It works just fine, but if I include this CollectionsView under the TabView, then the effect is exactly the same as in the example above. The view stops working properly: deleted items are added back on view redraw and adding new objects doesn't refresh the View.
This makes me think more of a bug in #ObservedResults().
Below is the source code.
class Collection: Object, ObjectKeyIdentifiable {
#objc dynamic var id: String = UUID().uuidString
#objc dynamic var name: String = ""
var actors = List<Actor>()
}
#main
struct CombatTrackerApp: App {
var body: some Scene {
WindowGroup {
Tabber() // will not work
// CollectionsView() // will work
}
}
}
struct CollectionsView: View {
#ObservedResults( Collection.self ) var collections
#State private var showNewCollectionForm = false
var body: some View {
NavigationStack {
List {
ForEach(collections) { collection in
Text(collection.name)
}.onDelete(perform: $collections.remove)
}
.listStyle(.inset)
.padding()
.navigationTitle("Collections")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button() {
self.showNewCollectionForm.toggle()
} label: {
Image(systemName: "plus")
Text("Add New Collection")
}
}
}
.sheet(isPresented: $showNewCollectionForm) {
NewCollectionView( showNewCollectionForm: $showNewCollectionForm )
}
}
}
}
struct NewCollectionView: View {
let realm = try! Realm()
#Binding var showNewCollectionForm: Bool
#State private var newCollectioName: String = ""
var body: some View {
NavigationStack {
VStack {
Text("Create new Collection").font(.title).padding()
Form {
TextField("Name", text: $newCollectioName)
}
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Close", role: .cancel) {
showNewCollectionForm.toggle()
}
}
ToolbarItem {
Button("Create") {
addCollection()
} .disabled(newCollectioName.isEmpty)
}
}
}
}
private func addCollection() {
let newCollection = Collection()
newCollection.name = newCollectioName
do {
try realm.write {
realm.add(newCollection)
}
} catch {
print("Cannot add new Collection", error)
}
showNewCollectionForm.toggle()
}
}
struct Tabber: View {
var body: some View {
TabView() {
NavigationStack {
CombatsListView()
}
.tabItem {
Text("Combats")
}
NavigationStack {
CollectionsView()
}
.tabItem {
Text("Collections")
}
SettingsView()
.tabItem {
Text("Settings")
}
}
}
}
I found out the solution (but I still don't understand why it's working).
The solution was to move NavigationStack from my TabView to the subviews. So instead of:
struct Tabber: View {
var body: some View {
TabView() {
NavigationStack {
CombatsListView()
}
.tabItem {
Text("Combats")
}
//...
I should do:
struct Tabber: View {
var body: some View {
TabView() {
CombatsListView()
.tabItem {
Text("Combats")
}
//...
struct CombatsListView: View {
var body: some View {
NavigationStack {
Confusing part was that all online tutorials and Apple Documentation suggests to wrap subviews with NavigationStack in TabView directly instead of adding NavigationStack in subviews. Maybe it's a bug, maybe it's a feature.
I am making a game with a minimal color scheme. I store the colors that I use as computed static var's in an enum so that I can call them in any view. I am trying to make a secondary color scheme (colorblind). My code looks like this:
enum GameColors {
static var exampleColor: Color {
!UserDefaults.standard.bool(forKey: GamePrefs.colorBlindMode) ? Color.green : Color(red: 0 / 255, green: 213 / 255, blue: 255 / 255)
}
}
enum GamePrefs {
static let colorBlindMode: String = "colorBlindMode"
}
My settings menu is called in my main menu view like so:
struct MainMenuView: View {
#State var settingsClicked: Bool = false
var body: some View {
VStack {
Button {
settingsClicked.toggle()
} label: {
Text("Settings")
.foregroundColor(GameColors.exampleColor)
}
if settingsClicked {
SettingsView()
}
}
}
}
struct SettingsView: View {
#AppStorage(GamePrefs.colorBlindMode) var colorBlindMode = false
var body: some View {
Toggle(isOn: $colorBlindMode) {
Text("Color Blind Mode: \(colorBlindMode ? "On" : "Off")")
.foregroundColor(GameColors.exampleColor)
}
}
}
When I toggle colorBlindMode, only SettingsView's colors are updated, the color of the main menu does not change unless I interact with it. How do I get both to update?
I've tried binding the #AppStorage property wrapper to no success.
You could try this approach, using #AppStorage and .onReceive in MainMenuView,
to ensure GameColors.exampleColor is updated/received in the MainMenuView while
clicking in the SettingsView.
struct MainMenuView: View {
#AppStorage(GamePrefs.colorBlindMode) var colorBlindMode = false // <-- here
#State var settingsClicked: Bool = false
var body: some View {
VStack {
Button {
settingsClicked.toggle()
} label: {
Text("Settings").foregroundColor(GameColors.exampleColor)
}
if settingsClicked {
SettingsView()
}
}
.onReceive(Just(colorBlindMode)) { _ in // <-- here
}
}
}
struct SettingsView: View {
#AppStorage(GamePrefs.colorBlindMode) var colorBlindMode = false
var body: some View {
Toggle(isOn: $colorBlindMode) {
Text("Color Blind Mode: \(colorBlindMode ? "On" : "Off")")
.foregroundColor(GameColors.exampleColor) // <-- here for testing
}
.toggleStyle(SwitchToggleStyle(tint: GameColors.exampleColor))
}
}
The reason your color does not change is because of your MainMenuView is not refreshing when you press the toggle. Only your SettingsView is refreshed. So you would need something to notify your MainMenuView that something has changed.
To do so you can add another AppStorage to your MainMenuView and force your view to refresh by creating a dependency on this property.
struct MainMenuView: View {
#State var settingsClicked: Bool = false
// add the same AppStorage as in SettingsView
#AppStorage(GamePrefs.colorBlindMode) var colorBlindMode = false
var body: some View {
VStack {
Button {
settingsClicked.toggle()
} label: {
let _ = print("text")
Text("Settings")
//this will force the view to update
.foregroundColor(colorBlindMode ? GameColors.exampleColor : GameColors.exampleColor)
}
if settingsClicked {
SettingsView()
}
}
}
}
After reading a bit more about what causes SwiftUI to reload a view, and a whole lot of testing different methods, I believe that the simplest way to solve this problem is to introduce a new #State variable which you must use somewhere in the parent view:
struct MainMenuView: View {
#State var settingsClicked: Bool = false
#State var reloadView: Bool = false // <-- here
var body: some View {
VStack {
Button {
settingsClicked.toggle()
} label: {
Text("Settings")
.foregroundColor(GameColors.exampleColor)
}
if settingsClicked {
SettingsView(reloadParentView: $reloadView)
}
if reloadView {} // <-- here
}
}
}
struct SettingsView: View {
#Binding var reloadParentView: Bool // <-- here
#AppStorage(GamePrefs.colorBlindMode) var colorBlindMode = false
var body: some View {
Toggle(isOn: $colorBlindMode) {
Text("Color Blind Mode: \(colorBlindMode ? "On" : "Off")")
.foregroundColor(GameColors.exampleColor)
}
.onChange(of: colorBlindMode) { _ in
reloadParentView.toggle() // <-- here
}
}
}
Passing this state from the parent view to the child view allows the child to force reloads on the parent at will.
I have a LazyVStack which I would like to only update one view and not have all others on screen reload. With more complex cells this causes a big performance hit. I have included sample code
import SwiftUI
struct ContentView: View {
#State var items = [String]()
var body: some View {
ScrollView {
LazyVStack {
ForEach(self.items, id: \.self) { item in
Button {
if let index = self.items.firstIndex(where: {$0 == item}) {
self.items[index] = "changed \(index)"
}
} label: {
cell(text: item)
}
}
}
}
.onAppear {
for _ in 0...200 {
self.items.append(NSUUID().uuidString)
}
}
}
}
struct cell: View {
let text: String
init(text: String) {
self.text = text
print("init cell", text)
}
var body: some View {
Text(text)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
As you can see even when only changing 1 cell the init gets called for every cell. Is there anyway to avoid this?
Here is a working code, there is some points to mention, View in SwiftUI would get initialized here and there or anytime SwiftUI thinks it needed! But the body of View would get computed if really some value in body changed. It is planed to work like that, there is some exceptions as well. Like body get computed even the values that used in the body were as before with no change, I do not want inter to that topic! But in your example and in your issue, we want SwiftUI renders only the changed View, for this goal the down code works well without issue, but as you can see I used VStack, if we change VStack to LazyVStack, SwiftUI would renders some extra view due its undercover codes, and if you scroll to down and then to up, it would forget all rendered view and data in memory and it will try to render the old rendered views, so it is the nature of LazyVStack, we cannot do much about it. Apple want LazyVStack be Lazy. But you can see that LazyVStack would not render all views, but some of them that needs to works. we cannot say or know how much views get rendered in Lazy way, but for sure not all of them.
let initializingArray: () -> [String] = {
var items: [String] = [String]()
for _ in 0...200 { items.append(UUID().uuidString) }
return items
}
struct ContentView: View {
#State var items: [String] = initializingArray()
var body: some View {
ScrollView {
VStack {
ForEach(items, id: \.self) { item in
Button(action: {
if let index = self.items.firstIndex(where: { $0 == item }) {
items[index] = "changed \(index)"
}
}, label: {
ItemView(item: item)
})
}
}
}
}
}
struct ItemView: View {
let item: String
var body: some View {
print("Rendering row for:", item)
return Text(item)
}
}
I've adapted an example from blog post which lets me share data associated with the selected element in a ForEach with another view on the screen. It sets up the FocusedValueKey conformance:
struct FocusedNoteValue: FocusedValueKey {
typealias Value = String
}
extension FocusedValues {
var noteValue: FocusedNoteValue.Value? {
get { self[FocusedNoteValue.self] }
set { self[FocusedNoteValue.self] = newValue }
}
}
Then it has a ForEach view with Buttons, where the focused Button uses the .focusedValue modifier to set is value to the NotePreview:
struct ContentView: View {
var body: some View {
Group {
NoteEditor()
NotePreview()
}
}
}
struct NoteEditor: View {
var body: some View {
VStack {
ForEach((0...5), id: \.self) { num in
let numString = "\(num)"
Button(action: {}, label: {
(Text(numString))
})
.focusedValue(\.noteValue, numString)
}
}
}
}
struct NotePreview: View {
#FocusedValue(\.noteValue) var note
var body: some View {
Text(note ?? "Note is not focused")
}
}
This works fine with the ForEach, but fails to work when the ForEach is replaced with List. How could I get this to work with List, and why is it unable to do so out of the box?
Goal: To use a common header View containing a shared title Text().
Scenario: I have multiple Views that share a common tab space within the one container tab View that contains a struct Header that is to be shared.
👉 This is a (many : 1) scenario.
Note: I don't want to use a NavigationView because it screws up landscape mode. A simple small header View is fine. I just need to populate the shared Title space amongst the member Views.
I don't want to merely add duplicate headers (having exactly the same layout) for each member View.
Several ideas: I need the header to respond to the 'change of title' event so I can see the new title.
So I believe I could use 1) #Binder(each member View) --> #State (shared Header View) or 2) #Environment.
I don't know how I could fit #1 into this particular scenario.
So I'm playing with #2: Environment Object.
DesignPattern: Main Header View's title set by multiple Views so the Header View is not aware of the multiple Views:
I'm not getting the EnvironmentObject paradigm to work.
Here's the codes...
MainView:
import SwiftUI
// Need to finish this.
class NYTEnvironment {
var title = "Title"
var msg = "Mother had a feeling..."
}
class NYTSettings: ObservableObject {
#Published var environment: NYTEnvironment
init() {
self.environment = NYTEnvironment()
}
}
struct NYTView: View {
var nytSettings = NYTSettings()
#State var selectionDataSegmentIndex = 0
var bindingDataSourceSegment: Binding<Int> {
.init(get: {
selectionDataSegmentIndex
}, set: {
selectionDataSegmentIndex = $0
})
}
var body: some View {
let county = 0; let state = 1; let states = 2
VStack {
NYTHeaderView()
SegmentAndDataPickerVStack(spacing: 10) {
if let segments = Source.NYT.dataSegments {
Picker("NYT Picker", selection: bindingDataSourceSegment) {
ForEach(segments.indices, id: \.self) { (index: Int) in
Text(segments[index])
}
}.pickerStyle(SegmentedPickerStyle())
}
}
if selectionDataSegmentIndex == county {
NYTCountyView()
} else if selectionDataSegmentIndex == state {
NYTStateView()
} else if selectionDataSegmentIndex == states {
NYTStatesView()
}
Spacer()
}.environmentObject(nytSettings)
}
struct TrailingItem: View {
var body: some View {
Button(action: {
print("Info")
}, label: {
Image(systemName: "info.circle")
})
}
}
}
// ====================================================================================
struct NYTHeaderView: View {
#EnvironmentObject var nytSettings: NYTSettings
var body: some View {
ZStack {
Color.yellow
Text(nytSettings.environment.title)
}.frame(height: Header.navigationBarHeight)
}
}
Revision: I've added EnvironmentObject modifiers to the memberViews():
if selectionDataSegmentIndex == county {
NYTCountyView().environmentObject(NYTSettings())
} else if selectionDataSegmentIndex == state {
NYTStateView().environmentObject(NYTSettings())
} else if selectionDataSegmentIndex == states {
NYTStatesView().environmentObject(NYTSettings())
}
...
One of the member Views that's within the Main Container/Tab View (per above):
struct NYTCountyView: View {
#ObservedObject var dataSource = NYTCountyModel()
#EnvironmentObject var nytSettings: NYTSettings
...
...
}.onAppear {
nytSettings.environment.title = "Selected Counties"
if dataSource.revisedCountyElementListAndDuration == nil {
dataSource.getData()
}
}
Spacer()
...
}
Here's the compile-time error:
Modus Operandi: Set the title w/in header per member View upon .onAppear().
Problem: I'm not getting any title; just the default "Title" value.
Question: Am I on the right track? If so, what am I missing?
or... is there an alternative?
The whole problem boils down to a 'Many : 1' paradigm.
I got this revelation via taking a break and going for a walk.
So this is the proverbial 'round peg in a square hole' scenario.
What I needed was a lightly coupled relationship where the origin of the title value isn't required. Hence the use of the Notification paradigm.
The header view's title is the receiver and hence I used the .onReceive modifier:
struct NYTHeaderView: View {
#State private var title: String = ""
var body: some View {
ZStack {
Color.yellow
Text(title).onReceive(NotificationCenter.default.publisher(for: .headerTitle)) {note in
title = note.object as? String ?? "New York Times"
}
}.frame(height: Header.navigationBarHeight)
}
}
This sounds like what SwiftUI preferences was built to solve. The preferences are values collected and reduced from children for some distant ancestor to use. One notable example of this is how NavigationView gets its title - the title is set on the child, not on the NavigationView itself:
NavigationView {
Text("I am a simple view")
.navigationTitle("Title")
}
So, in your case you have some kind of title (simplified to String for brevity) that each child view might want to set. So you'd define a TitlePreferenceKey like so:
struct TitlePreferenceKey: PreferenceKey {
static var defaultValue: String = ""
static func reduce(value: inout String, nextValue: () -> String) {
value = nextValue()
}
}
Here, the reduce function is simply applying the last value it sees from descendants, but since you'd only ever have one child view selected it should work.
Then, to use it, you'd have something like this:
struct NYTView: View {
#State var title = ""
#State var selection = 0
var body: some View {
VStack {
Text(title)
Picker("", selection: $selection) {
Text("SegmentA").tag(0)
Text("SegmentB").tag(1)
}
switch selection {
case 0: NYTCountyView()
case 1: NYTStateView()
.preference(key: TitlePreferenceKey.self, value: "State view")
default: EmptyView()
}
}
.onPreferenceChange(TitlePreferenceKey.self) {
self.title = $0
}
}
struct NYTCountyView: View {
#State var selectedCounty = "..."
var body: some View {
VStack {
//...
}
.preference(key: TitlePreferenceKey.self, value: selectedCounty)
}
}
So, a preference can be set by the parent of, as in the example of NYTStateView, or by the child with the value being dynamic, as in the example of NYTCountyView