How can I apply individual transitions to children views during insertion and removal in SwiftUI? - swiftui

I have a container view that contains multiple child views. These child views have different transitions that should be applied when the container view is inserted or removed.
Currently, when I add or remove this container view, the only transition that works is the one applied directly to the container view.
I have tried applying the transitions to each child view, but it doesn't work as expected. Here is a simplified version of my code:
struct Container: View, Identifiable {
let id = UUID()
var body: some View {
HStack {
Text("First")
.transition(.move(edge: .leading)) // this transition is ignored
Text("Second")
.transition(.move(edge: .trailing)) // this transition is ignored
}
.transition(.opacity) // this transition is applied
}
}
struct Example: View {
#State var views: [AnyView] = []
func pushView(_ view: some View) {
withAnimation(.easeInOut(duration: 1)) {
views.append(AnyView(view))
}
}
func popView() {
guard views.count > 0 else { return }
withAnimation(.easeInOut(duration: 1)) {
_ = views.removeLast()
}
}
var body: some View {
VStack(spacing: 30) {
Button("Add") {
pushView(Container()) // any type of view can be pushed
}
VStack {
ForEach(views.indices, id: \.self) { index in
views[index]
}
}
Button("Remove") {
popView()
}
}
}
}
And here's a GIF that shows the default incorrect behaviour:
If I remove the container's HStack and make the children tuple views, then the individual transitions will work, but I will essentially lose the container — which in this scenario was keeping the children aligned next to each other.
e.g
So this isn't a useful solution.
Note: I want to emphasise that the removal transitions are equally important to me

The .transition is applied to the View that appears (or disappears), and as you've found any .transition on a subview is ignored.
You can work around this by adding your Container without animation, and then animating in each of the Text.
struct Pair: Identifiable {
let id = UUID()
let first = "first"
let second = "second"
}
struct Container: View {
#State private var showFirst = false
#State private var showSecond = false
let pair: Pair
var body: some View {
HStack {
if showFirst {
Text(pair.first)
.transition(.move(edge: .leading))
}
if showSecond {
Text(pair.second)
.transition(.move(edge: .trailing))
}
}
.onAppear {
withAnimation {
showFirst = true
showSecond = true
}
}
}
}
struct ContentView: View {
#State var pairs: [Pair] = []
var animation: Animation = .easeInOut(duration: 1)
var body: some View {
VStack(spacing: 30) {
Button("Add") {
pairs.append(Pair())
}
VStack {
ForEach(pairs) { pair in
Container(pair: pair)
}
}
Button("Remove") {
if pairs.isEmpty { return }
withAnimation(animation) {
_ = pairs.removeLast()
}
}
}
}
}
Also note, your ForEach should be over an array of objects rather than Views (not that it makes a difference in this case).
Update
You can reverse the process by using a Binding to a Bool that contains the show state for each View. In this case I've created a struct PairState that holds a Set of all the views currently shown:
struct Container: View {
let pair: Pair
#Binding var show: Bool
var body: some View {
HStack {
if show {
Text(pair.first)
.transition(.move(edge: .leading))
Text(pair.second)
.transition(.move(edge: .trailing))
}
}
.onAppear {
withAnimation {
show = true
}
}
}
}
struct PairState {
var shownIds: Set<Pair.ID> = []
subscript(pairID: Pair.ID) -> Bool {
get {
shownIds.contains(pairID)
}
set {
shownIds.insert(pairID)
}
}
mutating func remove(_ pair: Pair) {
shownIds.remove(pair.id)
}
}
struct ContentView: View {
#State var pairs: [Pair] = []
#State var pairState = PairState()
var body: some View {
VStack(spacing: 30) {
Button("Add") {
pairs.append(Pair())
}
VStack {
ForEach(pairs) { pair in
Container(pair: pair, show: $pairState[pair.id])
}
}
Button("Remove") {
guard let pair = pairs.last else { return }
Task {
withAnimation {
pairState.remove(pair)
}
try? await Task.sleep(for: .seconds(0.5)) // 😢
_ = pairs.removeLast()
}
}
}
}
}
This has a delay in there to wait for the animation to complete before removing from the array. I'm not happy with that, but it works in this example.

Related

how to make the recursive view the same width?

I want to make a recursive view like this:
But what I have done is like this:
It's a tvOS application, the sample code is:
struct MainView: View {
#State private var selectedItem: ListItem?
var body: some View {
VStack {
RecursiveFolderListView(fileId: "root", selectedItem: $selectedItem)
}
}
}
struct RecursiveFolderListView: View {
#EnvironmentObject var api: API
var fileId: String
#Binding var selectedItem: ListItem?
#State private var currentPageSelectedItem: ListItem?
#State private var list: [ListItem]?
#State private var theId = 0
var body: some View {
HStack {
if let list = list, list.count > 0 {
ScrollView(.vertical) {
ForEach(list, id: \.self) { item in
Button {
selectedItem = item
currentPageSelectedItem = item
} label: {
HStack {
Text(item.name)
.font(.callout)
.multilineTextAlignment(.center)
.lineLimit(1)
Spacer()
if item.fileId == selectedItem?.fileId {
Image(systemName: "checkmark.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 30, height: 30)
.foregroundColor(.green)
}
}
.frame(height: 60)
}
}
}
.focusSection()
.onChange(of: currentPageSelectedItem) { newValue in
if list.contains(where: { $0 == newValue }) {
theId += 1
}
}
} else {
HStack {
Spacer()
Text("Empty")
Spacer()
}
}
if let item = currentPageSelectedItem, item.fileId != fileId {
RecursiveFolderListView(fileId: item.fileId, selectedItem: $selectedItem)
.id(theId)
}
}
.task {
list = try? await api.getFiles(parentId: fileId)
}
}
}
It's a list view, and when the user clicks one item in the list, it will expand the next folder list to the right. The expanded lists and the left one will have the same width.
I think it needs Geometryreader to get the full width, and pass down to the recursive hierarchy, but how to get how many views in the recursive logic?
I know why my code have this behavior, but I don't know how to adjust my code, to make the recursive views the same width.
Since you didn't include definitions of ListItem or API in your post, here are some simple definitions:
struct ListItem: Hashable {
let fileId: String
var name: String
}
class API: ObservableObject {
func getFiles(parentId: String) async throws -> [ListItem]? {
return try FileManager.default
.contentsOfDirectory(atPath: parentId)
.sorted()
.map { name in
ListItem(
fileId: (parentId as NSString).appendingPathComponent(name),
name: name
)
}
}
}
With those definitions (and changing the root fileId from "root" to "/"), we have a simple filesystem browser.
Now on to your question. Since you want each column to be the same width, you should put all the columns into a single HStack. Since you use recursion to visit the columns, you might think that's not possible, but I will demonstrate that it is possible. In fact, it requires just three simple changes:
Change VStack in MainView to HStack.
Change the outer HStack in RecursiveFolderListView to Group.
Move the .task modifier to the inner HStack around the "Empty" text, in the else branch.
The resulting code (with unchanged chunks omitted):
struct MainView: View {
#State private var selectedItem: ListItem? = nil
var body: some View {
HStack { // ⬅️ changed
RecursiveFolderListView(fileId: "/", selectedItem: $selectedItem)
}
}
}
struct RecursiveFolderListView: View {
...
var body: some View {
Group { // ⬅️ changed
if let list = list, list.count > 0 {
...
} else {
HStack {
Spacer()
Text("Empty")
Spacer()
}
.task { // ⬅️ moved to here
list = try? await api.getFiles(parentId: fileId)
}
}
}
// ⬅️ .task moved from here
}
}
I don't have the tvOS SDK installed, so I tested by commenting out the use of .focusSection() and running in an iPhone simulator:
This works because the subviews of a Group are “flattened” into the Group's parent container. So when SwiftUI sees a hierarchy like this:
HStack
Group
ScrollView (first column)
Group
ScrollView (second column)
Group
ScrollView (third column)
HStack (fourth column, "Empty")
SwiftUI flattens it into this:
HStack
ScrollView (first column)
ScrollView (second column)
ScrollView (third column)
HStack (fourth column, "Empty")
I moved the .task modifier because otherwise it would be attached to the Group, which would pass it on to all of its child views, but we only need the task applied to one child view.
Although rob's answer is perfect, I want to share another approach.
class SaveToPageViewModel: ObservableObject {
#Published var fileIds = [String]()
func tryInsert(fileId: String, parentFileId: String?) {
if parentFileId == nil {
fileIds.append(fileId)
} else if fileIds.last == parentFileId {
fileIds.append(fileId)
} else if fileIds.last == fileId {
// do noting, because this was caused by navigation bug, onAppear called twice
} else {
var copy = fileIds
copy.removeLast()
while copy.last != parentFileId {
copy.removeLast()
}
copy.append(fileId)
fileIds = copy
}
}
}
And wrap the container a GeometryReader and using the SaveToPageViewModel to follow the recursive view's length:
#State var itemWidth: CGFloat = 0
...
GeometryReader { proxy in
...
RecursiveFolderListView(fileId: "root", selectedItem: $selectedItem, parentFileId: nil, itemWidth: itemWidth)
.environmentObject(viewModel)
...
}
.onReceive(viewModel.$fileIds) { fileIds in
itemWidth = proxy.size.width / CGFloat(fileIds.count)
}
And in the RecursiveFolderListView, change the model data:
RecursiveFolderListView(fileId: item.fileId, selectedItem: $selectedItem, parentFileId: fileId, itemWidth: itemWidth)
.id(theId)
...
}
.onAppear {
model.tryInsert(fileId: fileId, parentFileId: parentFileId)
}

What's the best way to achieve parameterized "on tap"/"on click" behavior for a list row?

So let's say I have a list component in SwiftUI:
struct MyListView: View {
var body: some View {
List(...) { rec in
Row(rec)
}
}
}
Now let's say I want to make this reusable, and I want the "caller" of this view to determine what happens when I tap on each row view. What would be the correct way to insert that behavior?
Here is some other Buttons in ListView example that you can run and play with it yourself
import SwiftUI
struct TestTableView: View {
#State private var item: MyItem?
var body: some View {
NavigationView {
List {
// Cell as Button that display Sheet
ForEach(1...3, id:\.self) { i in
Button(action: { item = MyItem(number: i) }) {
TestTableViewCell(number: i)
}
}
// Cell as NavigationLink
ForEach(4...6, id:\.self) { i in
NavigationLink(destination: TestTableViewCell(number: i)) {
TestTableViewCell(number: i)
}
}
// If you want a button inside cell which doesn't trigger the whole cell when being touched
HStack {
TestTableViewCell(number: 7)
Spacer()
Button(action: { item = MyItem(number: 7) }) {
Text("Button").foregroundColor(.accentColor)
}.buttonStyle(PlainButtonStyle())
}
}
}.sheet(item: $item) { myItem in
TestTableViewCell(number: myItem.number)
}
}
struct MyItem: Identifiable {
var number: Int
var id: Int { number }
}
}
struct TestTableViewCell: View {
var number: Int
var body: some View {
Text("View Number \(number)")
}
}
Make it like Button and takes an action param that is a closure.
From my understanding you're looking for a reusable generic List view with tap on delete functionality. If I'm guessing right my approach then would be like this:
struct MyArray: Identifiable {
let id = UUID()
var title = ""
}
struct ContentView: View {
#State private var myArray = [
MyArray(title: "One"),
MyArray(title: "Two"),
MyArray(title: "Three"),
MyArray(title: "Four"),
MyArray(title: "Five"),
]
var body: some View {
MyListView(array: myArray) { item in
Text(item.title) // row view
} onDelete: { item in
myArray.removeAll(where: {$0.id == item.id}) // delete func
}
}
}
struct MyListView<Items, Label>: View
where Items: RandomAccessCollection, Items.Element: Identifiable, Label: View {
var array: Items
var row: (Items.Element) -> Label
var onDelete: (Items.Element) -> ()
var body : some View {
List(array) { item in
Button {
onDelete(item)
} label: {
row(item)
}
}
}
}

In SwiftUI, how to implement something like `navigationBarItems(...)`

I've had some problems with SwiftUI's navigation API, so I'm experimenting with implementing my own. Parts of this are relatively easy: I create a class NavModel that is basically a stack. Depending on what's on the top of that stack, I can display different views.
But I can't see how to implement something like SwiftUI's .navigationBarItems(...). That view modifier seems to use something like the Preferences API to pass its argument View up the hierarchy to the containing navigation system. Eg:
VStack {
...
}.navigationBarItems(trailing: Button("Edit") { startEdit() })
Anything that goes through onPreferenceChange(...) has to be Equatable, so if I want to pass an AnyView? for the navigation bar items, I need to somehow may it Equatable, and I don't see how to do that.
Here's some sample code that shows a basic push and pop navigation. I'm wondering: how could I make the navBarItems(...) work? (The UI is ugly, but that's not important now.)
struct ContentView: View {
#StateObject var navModel: NavModel = .shared
var body: some View {
NavView(model: navModel) { node in
switch node {
case .root: rootView
case .foo: fooView
}
}
}
var rootView: some View {
VStack {
Text("This is the root")
Button {
navModel.push(.foo)
} label: {
Text("Push a view")
}
}
}
var fooView: some View {
VStack {
Text("Foo")
Button {
navModel.pop()
} label: {
Text("Pop nav stack")
}
}.navBarItems(trailing: Text("Test"))
}
}
struct NavView<Content: View>: View {
#ObservedObject var model: NavModel
let makeViews: (NavNode) -> Content
init(model: NavModel, #ViewBuilder makeViews: #escaping (NavNode) -> Content) {
self.model = model
self.makeViews = makeViews
}
#State var navItems: AnyView? = nil
var body: some View {
VStack {
let node = model.stack.last!
navBar
Divider()
makeViews(node)
.frame(maxHeight: .infinity)
// This doesn't compile
.onPreferenceChange(NavBarItemsPrefKey.self) { v in
navItems = v
}
}
}
var navBar: some View {
HStack {
if model.stack.count > 1 {
Button {
model.pop()
} label: { Text("Back") }
}
Spacer()
if let navItems = self.navItems {
navItems
}
}
}
}
enum NavNode {
case root
case foo
}
class NavModel: ObservableObject {
static let shared = NavModel()
#Published var stack: [NavNode]
init() {
stack = [.root]
}
func push(_ node: NavNode) { stack.append(node) }
func pop() {
if stack.count > 1 {
stack.removeLast()
}
}
}
struct NavBarItemsPrefKey: PreferenceKey {
typealias Value = AnyView?
static var defaultValue: Value = nil
static func reduce(value: inout Value, nextValue: () -> Value) {
let n = nextValue()
if n != nil { // ???
value = n
}
}
}
// Is this the right way? But then anything passed to navBarItems(...) would need
// to be Equatable. The common case - Buttons - are not.
struct AnyEquatableView: Equatable {
???
init<T>(_ ev: EquatableView<T>) {
???
}
static func == (lhs: AnyEquatableView, rhs: AnyEquatableView) -> Bool {
???
}
}
struct NavBarItemsModifier<T>: ViewModifier where T: View {
let trailing: T
func body(content: Content) -> some View {
content.preference(key: NavBarItemsPrefKey.self, value: AnyView(trailing))
}
}
extension View {
func navBarItems<T>(trailing: T) -> some View where T: View {
return self.modifier(NavBarItemsModifier(trailing: trailing))
}
}

SwiftUI Observed Object not updating

Really just starting out with SwiftUI and trying to get my head around MVVM.
The code below displays a height and 4 toggle buttons, thus far I have only connected 2.
Major up and Major Down.
When clicked I see in the console that the value is altered as expected.
What I don't see is the the main display updating to reflect the change.
I have tried refactoring my code to include the view model into each Struct but still not seeing the change.
I think I have covered the basics but am stumped, I'm using a single file for now but plan to move the Model and ViewModel into separate files when I have a working mockup.
Thanks for looking.
import SwiftUI
/// This is our "ViewModel"
class setHeightViewModel: ObservableObject {
struct ImperialAndMetric {
var feet = 16
var inches = 3
var meters = 4
var CM = 95
var isMetric = true
}
// The model should be Private?
// ToDo: Fix the private issue.
#Published var model = ImperialAndMetric()
// Our getters for the model
var feet: Int { return model.feet }
var inches: Int { return model.inches }
var meters: Int { return model.meters }
var cm: Int { return model.CM }
var isMetric: Bool { return model.isMetric }
/// Depending upon the selected mode, move the major unit up by one.
func majorUp() {
if isMetric == true {
model.meters += 1
print("Meters is now: \(meters)")
} else {
model.feet += 1
print("Feet is now: \(feet)")
}
}
/// Depending upon the selected mode, move the major unit down by one.
func majorDown() {
if isMetric == true {
model.meters -= 1
print("Meters is now: \(meters)")
} else {
model.feet -= 1
print("Feet is now: \(feet)")
}
}
/// Toggle the state of the display mode.
func toggleMode() {
model.isMetric = !isMetric
}
}
// This is our View
struct ViewSetHeight: View {
// UI will watch for changes for setHeihtVM now.
#ObservedObject var setHeightVM = setHeightViewModel()
var body: some View {
NavigationView {
Form {
ModeArea(viewModel: setHeightVM)
SelectionUp(viewModel: setHeightVM)
// Show the correct height format
if self.setHeightVM.isMetric == true {
ValueRowMetric(viewModel: self.setHeightVM)
} else {
ValueRowImperial(viewModel: self.setHeightVM)
}
SelectionDown(viewModel: setHeightVM)
}.navigationTitle("Set the height")
}
}
}
struct ModeArea: View {
var viewModel: setHeightViewModel
var body: some View {
Section {
if viewModel.isMetric == true {
SwitchImperial(viewModel: viewModel)
} else {
SwitchMetric(viewModel: viewModel)
}
}
}
}
struct SwitchImperial: View {
var viewModel: setHeightViewModel
var body: some View {
HStack {
Button(action: {
print("Imperial Tapped")
}, label: {
Text("Imperial").onTapGesture {
viewModel.toggleMode()
}
})
Spacer()
Text("\(viewModel.feet)\'-\(viewModel.inches)\"").foregroundColor(.gray)
}
}
}
struct SwitchMetric: View {
var viewModel: setHeightViewModel
var body: some View {
HStack {
Button(action: {
print("Metric Tapped")
}, label: {
Text("Metric").onTapGesture {
viewModel.toggleMode()
}
})
Spacer()
Text("\(viewModel.meters).\(viewModel.cm) m").foregroundColor(.gray)
}
}
}
struct SelectionUp: View {
var viewModel: setHeightViewModel
var body: some View {
Section {
HStack {
Button(action: {
print("Major Up Tapped")
viewModel.majorUp()
}, label: {
Image(systemName: "chevron.up").padding()
})
Spacer()
Button(action: {
print("Minor Up Tapped")
}, label: {
Image(systemName: "chevron.up").padding()
})
}
}
}
}
struct ValueRowImperial: View {
var viewModel: setHeightViewModel
var body: some View {
HStack {
Spacer()
Text(String(viewModel.feet)).accessibility(label: Text("Feet"))
Text("\'").foregroundColor(Color.gray).padding(.horizontal, -10.0).padding(.top, -15.0)
Text("-").foregroundColor(Color.gray).padding(.horizontal, -10.0)
Text(String(viewModel.inches)).accessibility(label: Text("Inches"))
Text("\"").foregroundColor(Color.gray).padding(.horizontal, -10.0).padding(.top, -15.0)
Spacer()
}.font(.largeTitle).padding(.zero)
}
}
struct ValueRowMetric: View {
var viewModel: setHeightViewModel
var body: some View {
HStack {
Spacer()
Text(String(viewModel.meters)).accessibility(label: Text("Meter"))
Text(".").padding(.horizontal, -5.0).padding(.top, -15.0)
Text(String(viewModel.cm)).accessibility(label: Text("CM"))
Text("m").padding(.horizontal, -5.0).padding(.top, -15.0).font(.body)
Spacer()
}.font(.largeTitle)
}
}
struct SelectionDown: View {
var viewModel: setHeightViewModel
var body: some View {
Section {
HStack {
Button(action: {
print("Major Down Tapped")
viewModel.majorDown()
}, label: {
Image(systemName: "chevron.down").padding()
})
Spacer()
Button(action: {
print("Minor Down Tapped")
}, label: {
Image(systemName: "chevron.down").padding()
})
}
}
}
}
At the moment you receive the setHeightViewModel in various views as a var,
you should receive it as an ObservedObject.
I suggest you try this, in ViewSetHeight
#StateObject var setHeightVM = setHeightViewModel()
and in all your other views where you pass this model, use:
#ObservedObject var viewModel: setHeightViewModel
such as in ModeArea, SwitchImperial, SwitchMetric, SelectionUp, etc...
Alternatively you could use #EnvironmentObject ... to pass the setHeightViewModel
to all views that needs it.

SwiftUI ScrollView not getting updated?

Goal
Get data to display in a scrollView
Expected Result
Actual Result
Alternative
use List, but it is not flexible (can't remove separators, can't have multiple columns)
Code
struct Object: Identifiable {
var id: String
}
struct Test: View {
#State var array = [Object]()
var body: some View {
// return VStack { // uncomment this to see that it works perfectly fine
return ScrollView(.vertical) {
ForEach(array) { o in
Text(o.id)
}
}
.onAppear(perform: {
self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
})
}
}
A not so hacky way to get around this problem is to enclose the ScrollView in an IF statement that checks if the array is empty
if !self.array.isEmpty{
ScrollView(.vertical) {
ForEach(array) { o in
Text(o.id)
}
}
}
I've found that it works (Xcode 11.2) as expected if state initialised with some value, not empty array. In this case updating works correctly and initial state have no effect.
struct TestScrollViewOnAppear: View {
#State var array = [Object(id: "1")]
var body: some View {
ScrollView(.vertical) {
ForEach(array) { o in
Text(o.id)
}
}
.onAppear(perform: {
self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
})
}
}
One hacky workaround I've found is to add an "invisible" Rectangle inside the scrollView, with the width set to a value greater than the width of the data in the scrollView
struct Object: Identifiable {
var id: String
}
struct ContentView: View {
#State var array = [Object]()
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
Rectangle()
.frame(width: geometry.size.width, height: 0.01)
ForEach(array) { o in
Text(o.id)
}
}
}
.onAppear(perform: {
self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
})
}
}
The expected behavior occurs on Xcode 11.1 but doesn't on Xcode 11.2.1
I added a frame modifier to the ScrollView which make the ScrollView appear
struct Object: Identifiable {
var id: String
}
struct ContentView: View {
#State var array = [Object]()
var body: some View {
ScrollView(.vertical) {
ForEach(array) { o in
Text(o.id)
}
}
.frame(height: 40)
.onAppear(perform: {
self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
})
}
}
Borrowing from paulaysabellemedina, I came up with a little helper view that handles things the way I expected.
struct ScrollingCollection<Element: Identifiable, Content: View>: View {
let items: [Element]
let axis: Axis.Set
let content: (Element) -> Content
var body: some View {
Group {
if !self.items.isEmpty {
ScrollView(axis) {
if axis == .horizontal {
HStack {
ForEach(self.items) { item in
self.content(item)
}
}
}
else {
VStack {
ForEach(self.items) { item in
self.content(item)
}
}
}
}
}
else {
EmptyView()
}
}
}
}