Swiftui Scrollview Only Scroll in One Direction

SwiftUI ScrollView only scroll in one direction

This can be achieved with a GeometryReader. Wrap your ScrollView in one and then set the width of your VStack.

GeometryReader is a super easy, and pretty useful trick to have in your belt for SwiftUI :)

Here's how I got it working with your code:

NavigationView {
GeometryReader { geometry in
ScrollView {
VStack(alignment: .leading){
ForEach(self.friends) { friend in
NavigationButton(destination: MessageDetailView(friend: friend)) {
CustomListItem(friend: friend)
}
}
Spacer()
}.frame(width: geometry.size.width)
}
.foregroundColor(.black)
.navigationBarTitle(Text("Messages"))
}
}

UIScrollView scrolling in only one direction at a time

Set the directionalLockEnabled property to YES. From the Apple docs:

If this property is NO, scrolling is permitted in both horizontal and vertical directions. If this property is YES and the user begins dragging in one general direction (horizontally or vertically), the scroll view disables scrolling in the other direction. If the drag direction is diagonal, then scrolling will not be locked and the user can drag in any direction until the drag completes. The default value is NO

UIScrollView disable scrolling in just one direction?

Turns out a simple solution was actually possible and easy:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.y > 60) {
[scrollView setContentOffset:CGPointMake(0, 60)];
}
}

How to detect scroll direction programmatically in SwiftUI ScrollView

You would use GeometryReader to get the global position of one in the views in the ScrollView to detect the scroll direction. The code below will print out the current midY position. Dependent on the +/- value you could display or hide other views.

struct ContentView: View {

var body: some View {
ScrollView{
GeometryReader { geometry in

Text("Top View \(geometry.frame(in: .global).midY)")
.frame(width: geometry.size.width, height: 50)
.background(Color.orange)
}

}.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 0, maxHeight: .infinity, alignment: .center)
}

}

Stop vertical scroll in SwiftUI ScrollView

If ScrollView's height is less than the content's height it will scroll vertically too.

Just make it higher or the content narrower.

How to only disable scroll in ScrollView but not content view?

Only pass .horizontal as the scroll axis if you want the view to scroll. Otherwise, pass the empty set.

struct TestView: View {
@Binding var shouldScroll: Bool

var body: some View {
ScrollView(axes, showsIndicators: false) {
Text("Your content here")
}
}

private var axes: Axis.Set {
return shouldScroll ? .horizontal : []
}
}


Related Topics



Leave a reply



Submit