What is the correct way to update ScrollView in SwiftUI? (MacOS App) - swift

I am using officially released Xcode 11 from appstore.
A number of things can be seen if you run the code below.
Tapping on Root Press correctly adds the missing view#2, But there is no animation. Why is there no animation?
Tapping any of the Press buttons, correctly adds a middle view, but if you look, you will see that the scrollView content size did not update and therefore the content is clipped. What is the correct way to update the ScrollView?
import SwiftUI
struct ContentView: View {
#State var isPressed = false
var body: some View {
VStack {
Button("Root Press") { withAnimation { self.isPressed.toggle() } }
ScrollView {
Group {
SampleView(index: 1)
if isPressed { SampleView(index: 2) }
SampleView(index: 3)
SampleView(index: 4)
}
.border(Color.red)
}
}
}
}
struct SampleView: View {
#State var index: Int
#State var isPressed = false
var body: some View {
HStack {
VStack {
Text("********************")
Text("This View = \(index)")
Text("********************")
if isPressed {
Text("********************")
Text("-----> = \(index)")
Text("********************")
}
}
Button("Press") { withAnimation { self.isPressed.toggle() } }
}
}
}

Fixing the animations can be done via: .animation(.linear(duration: 0.3)). You can then remove all the animation blocks. (withAnimation { }). As for the bounds/frame, setting the frame helps (when adding the row at the root level), but it doesn't seem to work when you are dealing with an inner view. I added the following: .frame(width:UIScreen.main.bounds.width), and it will look like the following:

Related

Animate NSWindow's size change based on SwiftUI changes

By default, an NSWindow that hosts a SwiftUI view will automatically resize to fit the size of the view if/when it changes. However, if the changes are animated, the window jumps to the final size without animating. Is there a way to animate the window size along with the content?
I've tried this with and without SwiftUI's lifecycle. I'v also tried calling the toggle method with NSAnimationContext.runAnimationGroup
struct ContentView: View {
#State var isExpanded = false
var body: some View {
VStack {
Button(isExpanded ? "Close" : "Open", action: toggleExpand)
if isExpanded {
ForEach(0..<5) { count in
Text("\(count). Some Item")
}
}
}
.padding()
.fixedSize()
}
func toggleExpand() {
withAnimation(.easeInOut(duration: 1)) { isExpanded.toggle() }
}
}

Can you animate a SwiftUI View on disappear?

I have a SwiftUI View which has a custom animation that runs onAppear. I am trying to get the view to animate onDisappear too but it just immediately vanishes.
The below example reproduces the problem - the MyText view should slide in from the left and slide out to the right. The id modifier is used to ensure a new view is rendered each time the value changes, and I have confirmed that both onAppear and onDisappear are indeed called each time, but the animation onDisappear never visibly runs. How can I achieve this?
struct Survey: View {
#State private var id = 0
var body: some View {
VStack {
MyText(text: "\(id)").id(id)
Button("Increment") {
self.id += 1
}
}
}
struct MyText: View {
#State private var offset: CGFloat = -100
let text: String
var body: some View {
return Text(text)
.offset(x: offset)
.onAppear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 0
}
}
.onDisappear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 100
}
}
}
}
}
Probably you wanted transition, something like
Update: re-tested with Xcode 13.4 / iOS 15.5
struct Survey: View {
#State private var id = 0
var body: some View {
VStack {
MyText(text: "\(id)")
Button("Increment") {
self.id += 1
}
}
}
struct MyText: View {
var text: String
var body: some View {
Text("\(text)").id(text)
.frame(maxWidth: .infinity)
.transition(.slide)
.animation(.easeInOut(duration: 2), value: text)
}
}
}
I'm afraid it can't work since the .onDisappear modifier is called once the view is hidden.
However there is a nice answer here :
Is there a SwiftUI equivalent for viewWillDisappear(_:) or detect when a view is about to be removed?

How to animate hideable views with SwiftUI?

I'm trying out SwiftUI, and while I've found many of its features very elegant, I've had trouble with animations and transitions. Currently, I have something like
if shouldShowText { Text(str).animation(.default).transition(AnyTransition.opacity.animation(.easeInOut)) }
This label does transition properly, but when it's supposed to move (when another view above is hidden, for instance) it does not animate as I would have expected, but rather jumps into place. I've noticed that wrapping everything in an HStack works, but I don't see why that's necessary, and I was hoping that there is a better solution out there.
Thanks
If I correctly understood and reconstructed your scenario you need to use explicit withAnimation (depending on the needs either for "above view" or for both) as shown below
struct SimpleTest: View {
#State var shouldShowText = false
#State var shouldShowAbove = true
var body: some View {
VStack {
HStack
{
Button("ShowTested") { withAnimation { self.shouldShowText.toggle() } }
Button("HideAbove") { withAnimation { self.shouldShowAbove.toggle() } }
}
Divider()
if shouldShowAbove {
Text("Just some above text").padding()
}
if shouldShowText {
Text("Tested Text").animation(.default).transition(AnyTransition.opacity.animation(.easeInOut))
}
}
}
}

SwiftUI: Animate Cells within a Form

I am trying to animate my Form or rather the cells within it. My problem is that the following code give me a nice insertion animation but for the removal the cell is suddenly removed after am ugly looking delay.
import SwiftUI
struct ContentView: View {
#State var toggledValue = false
#State var pickedValue = 0
var body: some View {
NavigationView {
Form {
Section {
Toggle(isOn: $toggledValue) {
Text("Toggled Value")
}
if toggledValue {
Picker(selection: $pickedValue, label: Text("Picked Value")) {
ForEach((0...5).identified(by: \.self)) {
Text("Pick Value \($0)").tag($0)
}
}
}
}
Section {
Text("Some Text")
}
}
.navigationBarTitle("Navigation Bar Title")
}
}
}
What I tried so far is to to wrap the Toggle in a withAnimation closure but this does not change anything. What makes me wondering is that the same code using List instead of Form gives me the expected Animation. Is that a bug or am I overseeing something?
This will probably work (tested in iOS 16 in a similar situation):
Add #State private var isShowingPicker = false
Replace if toggledValue by if isShowingPicker
Under .navigationBarTitle(...) add:
onChange(of: toggledValue)
{ newValue in
withAnimation { isShowingPicker = newValue }
}

In SwiftUI, where are the control events, i.e. scrollViewDidScroll to detect the bottom of list data

In SwiftUI, does anyone know where are the control events such as scrollViewDidScroll to detect when a user reaches the bottom of a list causing an event to retrieve additional chunks of data? Or is there a new way to do this?
Seems like UIRefreshControl() is not there either...
Plenty of features are missing from SwiftUI - it doesn't seem to be possible at the moment.
But here's a workaround.
TL;DR skip directly at the bottom of the answer
An interesting finding whilst doing some comparisons between ScrollView and List:
struct ContentView: View {
var body: some View {
ScrollView {
ForEach(1...100) { item in
Text("\(item)")
}
Rectangle()
.onAppear { print("Reached end of scroll view") }
}
}
}
I appended a Rectangle at the end of 100 Text items inside a ScrollView, with a print in onDidAppear.
It fired when the ScrollView appeared, even if it showed the first 20 items.
All views inside a Scrollview are rendered immediately, even if they are offscreen.
I tried the same with List, and the behaviour is different.
struct ContentView: View {
var body: some View {
List {
ForEach(1...100) { item in
Text("\(item)")
}
Rectangle()
.onAppear { print("Reached end of scroll view") }
}
}
}
The print gets executed only when the bottom of the List is reached!
So this is a temporary solution, until SwiftUI API gets better.
Use a List and place a "fake" view at the end of it, and put fetching logic inside onAppear { }
You can to check that the latest element is appeared inside onAppear.
struct ContentView: View {
#State var items = Array(1...30)
var body: some View {
List {
ForEach(items, id: \.self) { item in
Text("\(item)")
.onAppear {
if let last == self.items.last {
print("last item")
self.items += last+1...last+30
}
}
}
}
}
}
In case you need more precise info on how for the scrollView or list has been scrolled, you could use the following extension as a workaround:
extension View {
func onFrameChange(_ frameHandler: #escaping (CGRect)->(),
enabled isEnabled: Bool = true) -> some View {
guard isEnabled else { return AnyView(self) }
return AnyView(self.background(GeometryReader { (geometry: GeometryProxy) in
Color.clear.beforeReturn {
frameHandler(geometry.frame(in: .global))
}
}))
}
private func beforeReturn(_ onBeforeReturn: ()->()) -> Self {
onBeforeReturn()
return self
}
}
The way you can leverage the changed frame like this:
struct ContentView: View {
var body: some View {
ScrollView {
ForEach(0..<100) { number in
Text("\(number)").onFrameChange({ (frame) in
print("Origin is now \(frame.origin)")
}, enabled: number == 0)
}
}
}
}
The onFrameChange closure will be called while scrolling. Using a different color than clear might result in better performance.
edit: I've improved the code a little bit by getting the frame outside of the beforeReturn closure. This helps in the cases where the geometryProxy is not available within that closure.
I tried the answer for this question and was getting the error Pattern matching in a condition requires the 'case' keyword like #C.Aglar .
I changed the code to check if the item that appears is the last of the list, it'll print/execute the clause. This condition will be true once you scroll and reach the last element of the list.
struct ContentView: View {
#State var items = Array(1...30)
var body: some View {
List {
ForEach(items, id: \.self) { item in
Text("\(item)")
.onAppear {
if item == self.items.last {
print("last item")
fetchStuff()
}
}
}
}
}
}
The OnAppear workaround works fine on a LazyVStack nested inside of a ScrollView, e.g.:
ScrollView {
LazyVStack (alignment: .leading) {
TextField("comida", text: $controller.searchedText)
switch controller.dataStatus {
case DataRequestStatus.notYetRequested:
typeSomethingView
case DataRequestStatus.done:
bunchOfItems
case DataRequestStatus.waiting:
loadingView
case DataRequestStatus.error:
errorView
}
bottomInvisibleView
.onAppear {
controller.loadNextPage()
}
}
.padding()
}
The LazyVStack is, well, lazy, and so only create the bottom when it's almost on the screen
I've extracted the LazyVStack plus invisible view in a view modifier for ScrollView that can be used like:
ScrollView {
Text("Some long long text")
}.onScrolledToBottom {
...
}
The implementation:
extension ScrollView {
func onScrolledToBottom(perform action: #escaping() -> Void) -> some View {
return ScrollView<LazyVStack> {
LazyVStack {
self.content
Rectangle().size(.zero).onAppear {
action()
}
}
}
}
}