简体   繁体   中英

How ScrollView Layout Direction to right-to-left in SwiftUI?

How can we set right to left layout direction in Horizontal ScrollView in swiftUI?

something like this:

ScrollView(showsHorizontalIndicator: false) {
    HStack {
        VStack {
            Image("1")
            Text("one")
        }
        VStack {
            Image("2")
            Text("two")
        }
        VStack {
            Image("3")
            Text("three")
        }
    }
}

so when simulator run, I want to see Image("1") in right hand side and swipe to right to can access to Image("3")

You can make any view you want right-to-left by giving your view below modifiers:

.flipsForRightToLeftLayoutDirection(true)
.environment(\.layoutDirection, .rightToLeft)

In your case, it is going to be like this:

ScrollView(showsHorizontalIndicator: false) {
    HStack {
        VStack {
            Image("1")
            Text("one")
        }
        VStack {
            Image("2")
            Text("two")
        }
        VStack {
            Image("3")
            Text("three")
        }
    }
}
.flipsForRightToLeftLayoutDirection(true)
.environment(\.layoutDirection, .rightToLeft)

GoodLuck dadash ;)

You can also use the my helper.

import SwiftUI

struct ScrollViewRTL<Content: View>: View {
  @ViewBuilder var content: Content
  @Environment(\.layoutDirection) private var layoutDirection
  var type: RowType
   
  init(type: RowType, @ViewBuilder content: () -> Content) {
    self.type = type
    self.content = content()
  }
   
  @ViewBuilder var body: some View {
    ScrollView(type.scrollAxis, showsIndicators: false) {
      content
        .rotation3DEffect(Angle(degrees: layoutDirection == .rightToLeft ? -180 : 0), axis: (
          x: CGFloat(0),
          y: CGFloat(layoutDirection == .rightToLeft ? -10 : 0),
          z: CGFloat(0)))
       
    }
    .rotation3DEffect(Angle(degrees: layoutDirection == .rightToLeft ? 180 : 0), axis: (
      x: CGFloat(0),
      y: CGFloat(layoutDirection == .rightToLeft ? 10 : 0),
      z: CGFloat(0)))
  }
}

public enum RowType {
  case hList
  case vList
   
  var scrollAxis: Axis.Set {
    switch self {
    case .hList:
      return .horizontal
       
    case .vList:
      return .vertical
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM