How can I hide my arrow text after ScrollView has scrolled?
struct Skroll: View {
var body: some View {
VStack(alignment: .trailing) {
Text("<-")
.font(.system(size: 25).bold())
.kerning(-3)
ScrollView(.horizontal, showsIndicators: false) {
HStack {
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
}
}
}
.padding()
}
}
I can't figure out how can I hide text after scrolling, I'm new and just learning SwiftUI
Looks like what you need is to get the current position of the scroll view. See here on how to do that. Then you can choose to display Text("<-") based on a flag which is modified when ScollView reaches a certain point
if !hideText {
Text("<-")
.font(.system(size: 25).bold())
.kerning(-3)
}
It might be also possible that you might achieve the same result by moving your Text("<-") inside the scroll view. See if below works for you
ScrollView(.horizontal, showsIndicators: false) {
Text("<-")
.font(.system(size: 25).bold())
.kerning(-3)
HStack {
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
}
}
I think I figured out how to do it
struct Skroll: View {
#State var scrollViewOffset: CGFloat = 0
#State var start: CGFloat = 0
var body: some View {
VStack(alignment: .trailing) {
HStack {
Image(systemName: "arrowtriangle.right.fill")
.font(.system(size: 35).bold())
.opacity(-scrollViewOffset > 160.0 ? 1 : 0)
.animation(.easeOut, value: scrollViewOffset)
Spacer()
Image(systemName: "arrowtriangle.left.fill")
.font(.system(size: 35))
.opacity(-scrollViewOffset > 160.0 ? 0 : 1)
.animation(.easeOut, value: scrollViewOffset)
}
ScrollView(.horizontal, showsIndicators: false) {
HStack {
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
Rectangle()
.frame(width: 200, height: 300)
.cornerRadius(20)
}
.overlay(GeometryReader { proxy -> Color in
DispatchQueue.main.async {
if start == 0 {
self.start = proxy.frame(in: .global).minX
}
let offset = proxy.frame(in: .global).minX
self.scrollViewOffset = offset - start
print(self.scrollViewOffset)
}
return Color.clear
})
}
}
.padding()
}
}
result
I replaced my text with an image. I'm not sure if this is the right solution and I don't know if it might cause any errors, but this works for me. Maybe someone will find it useful too
Related
I am seeing an odd crash with some beta testers on TestFlight. It seems to be at app startup, but prior to the point where we are making any network calls. There does not seem to be a lot on the internet regarding this, and symbolication isn't helping much either. Just curious if anyone has run into this before and what they did about it? I have had it happen on two tester's devices and I have never been able to recreate the issue locally.
For a bit of context, I am creating a list view on my main screen with a LazyVGrid that contains a LazyHGrid inside of it that are both filled using published vars from my viewmodel, though this seems to happen prior to any of those being created.
Thanks for any ideas / help
Edit: Some more details / actual code:
The view with the grids:
import SwiftUI
import Kingfisher
struct FeaturedView: View {
#EnvironmentObject var viewRouter: ViewRouter
#EnvironmentObject var tabRouter : TabRouter
#StateObject var loadingViewModel = LoadingViewModel()
private let imageProcessor = SVGImgProcessor()
private let playerManager = PlayerManager.shared
private var gridItemLayout = [GridItem(.flexible())]
let userDefaults = UserDefaults.standard
var body: some View {
let padding: CGFloat = 20
let paddingHStack: CGFloat = 25
GeometryReader { geometry in
ZStack(alignment: .top){
Color(hex:"#00091C").edgesIgnoringSafeArea(.all)
VStack {
HStack {
HStack {
Text("Hello, \(loadingViewModel.name)")
.frame(alignment: .leading)
.multilineTextAlignment(.center)
.font(Font.custom("poppins-medium", size: 20))
.foregroundColor(Color(hex:"#667C95"))
.padding(.leading, 15)
.padding(.top, 15)
.padding(.bottom, 15)
Image("PremiumStar")
.resizable()
.frame(width: 15.0, height: 15.0)
.opacity(userDefaults.isSubscriber() ? 1 : 0)
}
Spacer()
Button(action: {
print("Settings Clicked")
viewRouter.currentPage = .settingsFlow
}) {
Image("Settings")
.resizable()
.frame(width: 22.0, height: 22.0)
.padding(15)
}
}
ScrollView(showsIndicators: false) {
VStack(spacing: 10) {
LazyVGrid(columns: gridItemLayout, spacing: 17) {
ForEach(loadingViewModel.getCategories()) { category in
Text(category.title)
.foregroundColor(.white)
.font(Font.custom("poppins-bold", size: 30))
ZStack {
KFImage(URL(string: (category.background?.svg!)!))
.resizable()
.setProcessor(imageProcessor)
.frame(width: geometry.size.width - padding, height: 175, alignment: .topLeading)
.aspectRatio(contentMode: .fill)
.clipped()
.cornerRadius(5)
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: gridItemLayout, spacing: 20){
ForEach(loadingViewModel.getSoundsForCategory(category: category.key)) { sound in
Button(action: {
playerManager.play(sound: sound)
}) {
VStack {
ZStack{
RoundedRectangle(cornerRadius: 5).frame(width: 90, height: 90)
.foregroundColor(Color.black)
.opacity(0.85)
ZStack(alignment:.bottomTrailing){
KFImage(URL(string: sound.icon.png!)!)
.resizable()
.renderingMode(.template)
.foregroundColor(.white)
.frame(width: 75, height: 75)
.aspectRatio(contentMode: .fill)
.clipped()
Image("LockIcon")
.frame(width: 12, height: 12, alignment: .bottomTrailing)
.aspectRatio(contentMode: .fill)
.clipped()
.hidden(loadingViewModel.isSubscriber || sound.tier != 2)
}
}
Text(sound.name)
.foregroundColor(.white)
.font(Font.custom("poppins-regular", size: 12))
.lineLimit(1)
.frame(minWidth: 0, idealWidth: 90, maxWidth: 100, alignment: .center)
}
}
}
}.padding(.horizontal)
}
.frame(width: geometry.size.width - paddingHStack, height: 175, alignment: .topLeading)
}
Button("Explore All"){
print("Explore All \(category.title) Tapped")
tabRouter.categoryKey = category.key
tabRouter.hasChanged = true
tabRouter.currentTab = 1
}
.font(Font.custom("poppins-bold", size: 15))
.foregroundColor(Color.white)
}
}.padding(.bottom, 120)
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
FeaturedView()
}
}
That is loaded by this tab view, which goes between two screens which share the same viewModel / load the same data
// MARK: Tab View
var body: some View {
ZStack{
TabView(selection: $selectedTab){
FeaturedView()
.environmentObject(tabRouter)
.tabItem{
Label("FEATURED", image: "Featured")
}.tag(0)
.overlay(
VStack {
if (showOverlay && !isExpanded){
playView
} else {
EmptyView()
}
}
)
SoundView()
.environmentObject(tabRouter)
.tabItem{
Label("SOUNDS", image: "Sounds")
}.tag(1)
.overlay(
VStack {
if (showOverlay && !isExpanded){
playView
} else {
EmptyView()
}
}
)
}
}
}
I am complete beginner with SwiftUI and I can't wrap my head around how to connect these images with views that represents lines. Now I simply have 3 VStacks with image and text and put them into a HStack, but don't know how to connect these images with a line shown in red in the picture I attached. Note that there's some space between the line and the image. I need general direction and some hints, full working code not necessary.
Thank you.
How's this?
In SwiftUI, you use HStacks and VStacks to stack your Views. For the red line, a Rectangle should do. Here's the code:
struct ContentView: View {
var body: some View {
HStack { /// horizontal stack
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
Rectangle()
.fill(Color.red)
.frame(height: 5)
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
Rectangle()
.fill(Color.red)
.frame(height: 5)
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 800, height: 200))
}
}
Version 1.0.0
I decided to give my answer which is same like aheze answer with this difference that you can have CustomVerticalAlignment as well! As I see in your Image in question you want that also:
with CustomVerticalAlignment: In center!
without CustomVerticalAlignment: off center!
import SwiftUI
struct ContentView: View {
var body: some View {
HStack(alignment: .customVerticalAlignment) {
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
Capsule()
.fill(Color.red)
.frame(height: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
Capsule()
.fill(Color.red)
.frame(height: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
}
.padding()
}
}
extension VerticalAlignment {
struct CustomVerticalAlignment: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[VerticalAlignment.center]
}
}
static let customVerticalAlignment = VerticalAlignment(CustomVerticalAlignment.self)
}
Update Version 2.0.0
About this version: I would say it does the same job of version 1.0.0 in less code and also Text and Line are not depending on VStack or eachother any moere!
import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
image.overlay(text.offset(y: 40), alignment: .bottom)
capsule
image.overlay(text.offset(y: 40), alignment: .bottom)
capsule
image.overlay(text.offset(y: 40), alignment: .bottom)
}
.padding(50)
}
var image: some View {
return Image(systemName: "star.fill")
.resizable()
.scaledToFit()
.padding(10)
.shadow(radius: 10)
.frame(width: 50, height: 50, alignment: .center)
.foregroundColor(Color.red)
.background(Color.yellow)
.border(Color.black, width: 5)
}
var capsule: some View {
return Capsule()
.fill(Color.red)
.frame(height: 5)
}
var text: some View {
return Text("Hello World!")
.lineLimit(1)
.fixedSize()
}
}
You could define a Shape that represents your line.
I used the spacing parameter of HStack to do the spacing:
struct MyLine : Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 0, y: rect.midY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
}
}
}
struct ContentView: View {
var body: some View {
HStack(spacing: 10) {
VStack {
Image(systemName: "pencil")
Text("Label")
}
MyLine().stroke(Color.red)
VStack {
Image(systemName: "pencil")
Text("Label 2")
}
MyLine().stroke(Color.red)
VStack {
Image(systemName: "pencil")
Text("Label 3")
}
}
}
}
You could add a lineWidth parameter to make the stroke thicker:
.stroke(Color.red, lineWidth: 4)
Also, if you didn't using spacing on the HStack, you could using a padding modifier on either the VStacks or the MyLines to get the spacing.
I have a SwiftUI application. It has a ScrollView and a Text and I want the Text to display the position of the elements in the ScrollView.
struct LinkedScrolling: View {
#State var scrollPosition: CGFloat = 0
var body: some View {
VStack {
Text("\(self.scrollPosition)")
ScrollContent(scrollPosition: self.$scrollPosition)
}
}
}
This View contains the Text and the ScrollContent. This is ScrollContent:
struct ScrollContent: View {
#Binding var scrollPosition: CGFloat
var body: some View {
ScrollView(.horizontal) {
GeometryReader { geometry -> AnyView in
self.scrollPosition = geometry.frame(in: .global).minX
let view = AnyView(HStack(spacing: 20) {
Rectangle()
.fill(Color.blue)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.red)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.green)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.orange)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.pink)
.frame(width: 400, height: 200)
})
return view
}.frame(width: 5*400+4*20)
}
}
}
The State variable scrollPosition gets updated every time the elements in the ScrollView move.
When using the app in an iOS 14.2 Simulator, scrollPosition does not change and the console logs [SwiftUI] Modifying state during view update, this will cause undefined behavior..
What really confuses me, is that it works in the Xcode preview canvas and the State variable and the Text change like I want them to.
Is it possible to change the State variable this way?
If yes, how can I try to make it work on the Simulator?
If no, is there any other way to achieve my goal?
Thank you for your help!
You can use DispatchQueue.main.async.
DispatchQueue.main.async {
self.scrollPosition = geometry.frame(in: .global).minX
}
Or better way is to use .onReceive
Like this
struct ScrollContent: View {
#Binding var scrollPosition: CGFloat
var body: some View {
ScrollView(.horizontal) {
GeometryReader { geometry in
HStack(spacing: 20) {
Rectangle()
.fill(Color.blue)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.red)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.green)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.orange)
.frame(width: 400, height: 200)
Rectangle()
.fill(Color.pink)
.frame(width: 400, height: 200)
}.onReceive(Just(geometry), perform: { _ in //<-- Here
self.scrollPosition = geometry.frame(in: .global).minX
})
}.frame(width: 5*400+4*20)
}
}
}
Im working on a project with a similar layout to this where I have a few views stacked within a VStack and a button on the bottom, all embedded in a scrollview.
as you can see in the image the scrollview springs back and doesn't show the button.
var body: some View {
VStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Spacer()
ScrollView {
RectanglesView()
Button(action: /*#START_MENU_TOKEN#*/{}/*#END_MENU_TOKEN#*/) {
Text("Click me")
}
.offset(y: 50)
.frame(width: 300)
}
}.edgesIgnoringSafeArea(.all)
}
I do believe that the issue is due to the button's offset since it behaves normally if I remove it, but I don't want to lose the placement of the button.
Instead of offset, add padding, like this and within a VStack (slightly amended code below)
var body: some View {
ZStack{
VStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Spacer()
ScrollView {
VStack{
Rectangle()
.fill(Color.red)
.frame(height: 300)
Rectangle()
.fill(Color.yellow)
.frame(height: 300)
Button(action: /*#START_MENU_TOKEN#*/{}/*#END_MENU_TOKEN#*/) {
Text("Click me")
}.padding() //instead of offset
.frame(width: 300)
}.frame(alignment: .leading)
}
}.edgesIgnoringSafeArea(.all)
}
}
Have you tried moving the Button out of the ScrollView()?
Here is what looks like:
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Spacer()
ScrollView(.vertical) {
Rectangle().fill(Color.red).frame(width: 400, height: 200)
Rectangle().fill(Color.blue).frame(width: 400, height: 200)
Rectangle().fill(Color.yellow).frame(width: 400, height: 200)
Rectangle().fill(Color.green).frame(width: 400, height: 200)
}
Button(action: /*#START_MENU_TOKEN#*/{}/*#END_MENU_TOKEN#*/) {
Text("Click me")
.font(.headline)
}
}.edgesIgnoringSafeArea(.all)
}
}
I'm trying to add a new view inside the Scroll View that contains a button every time that I click in the blue button in the bottom
]1
Here i create the scroll view with 2 buttons, and want to add more after I click in the button on the right
HStack{
ScrollView(.horizontal, content: {
HStack{
PageStep()
PageStep()
}
})
Button(action: {
self.addNewStep = true
}) {
Image(systemName: "plus.square")
.frame(width: 75, height: 75)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 5)
)
}.buttonStyle(PlainButtonStyle()).padding(.trailing, 10)
}
.padding(.leading, 10)
.frame(minWidth: 0, maxWidth: UIScreen.main.bounds.width, minHeight: 80, alignment: .bottom)
.foregroundColor(Color.blue)
struct PageStep: View {
var stepPossition = String()
var body: some View {
Button(action: {
print("Entrou")
}){
Rectangle()
.fill(Color.red)
.frame(width: 75, height: 75)
.cornerRadius(10)
}
}
}
Here is possible approach. Tested with Xcode 11.4.
struct ContentView: View {
#State private var steps = 2 // pages counter
var body: some View {
HStack{
ScrollView(.horizontal, content: {
HStack{
// create available pages
ForEach(0..<steps, id: \.self) { i in
PageStep(stepPossition: "\(i)").id(i) // inject
}
}
})
Button(action: {
self.steps += 1 // << add next page
}) {
Image(systemName: "plus.square")
.frame(width: 75, height: 75)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 5)
)
}.buttonStyle(PlainButtonStyle()).padding(.trailing, 10)
}
.padding(.leading, 10)
.frame(minWidth: 0, maxWidth: UIScreen.main.bounds.width, minHeight: 80, alignment: .bottom)
.foregroundColor(Color.blue)
}
}
struct PageStep: View {
var stepPossition: String
var body: some View {
Button(action: {
print("Entrou")
}){
Rectangle()
.fill(Color.red)
.frame(width: 75, height: 75)
.cornerRadius(10)
}
}
}