import SwiftUI
struct ContentView: View {
let letters = Array("Testing stuff")
#State private var enabled = false
#State private var dragAmount = CGSize.zero
var body: some View {
HStack(spacing: 0)
{
ForEach(0..<letters.count) { num in
Text(String(letters[num]))
.padding(5)
.font(.title)
.background(enabled ? .blue : .red)
.offset(dragAmount)
.clipShape(Circle())
.animation(.default.delay(Double(num) / 20), value: dragAmount)
}
}
.gesture(
DragGesture()
.onChanged { dragAmount = $0.translation}
.onEnded { _ in
dragAmount = .zero
enabled.toggle()
}
)
}
}
So I have this piece of code, I'm mostly just testing out animation stuff, originally the clipShape modifier was before the offset modifier and everything worked and went as expected, but when I move the clipShape modifier to be after the offset everything still animates but it seems like it's stuck in the Shape and I can't see anything outside the Circle.
Could someone maybe explain exactly why this is?
I understand the order of the modifiers is obviously very important in SwiftUI but to me it seems like whenever dragAmount changes then each view gets redrawn and offset and that offset modifier just notices changes in dragAmount and when it notices one it just offsets but why is it a problem if I put clipShape after that? Shouldn't it still totally be fine? I obviously don't understand why the order of the modifiers is important in this case so it would be nice if someone could clarify.
It doesn't work because the text is offsetted, and then clipShape clips the original location for the text.
Paul Hudson sums it up well:
Using offset() will cause a view to be moved relative to its natural position, but won’t affect the position of other views or any other modifiers placed after the offset.
- https://www.hackingwithswift.com/quick-start/swiftui/how-to-adjust-the-position-of-a-view-using-its-offset
Here, the only part you can see if the part of the yellow rectangle that is inside of the circle (outlined in red).
If you want the content to be clipped, then offsetted, use the clipShape modifier before the offset modifier.
Then it should look something like this (the part you can see is outlined in red):
Related
Here I have this question when I try to give a View an initial position, then user can use drag gesture to change the location of the View to anywhere. Although I already solved the issue by only using .position(x:y:) on a View, at the beginning I was thinking using .position(x:y:) to give initial position and .offset(offset:) to make the View move with gesture, simultaneously. Now, I really just want to know in more detail, what exactly happens when I use both of them the same time (the code below), so I can explain what happens in the View below.
What I cannot explain in the View below is that: when I simply drag gesture on the VStack box, it works as expected and the VStack moves with finger gesture, however, once the gesture ends and try to start a new drag gesture on the VStack, the VStack box goes back to the original position suddenly (like jumping to the original position when the code is loaded), then start moving with the gesture. Note that the gesture is moving as regular gesture, but the VStack already jumped to a different position so it starts moving from a different position. And this causes that the finger tip is no long on top of the VStack box, but off for some distance, although the VStack moves with the same trajectory as drag gesture does.
My question is: why the .position(x:y:) modifier seems only take effect at the very beginning of each new drag gesture detected, but during the drag gesture action on it seems .offset(offset:) dominates the main movement and the VStack stops at where it was dragged to. But once new drag gesture is on, the VStack jumps suddenly to the original position. I just could not wrap my head around how this behavior happens through timeline. Can somebody provide some insights?
Note that I already solved the issue to achieve what I need, right now it's just to understand what is exactly going on when .position(x:y:) and .offset(offset:) are used the same time, so please avoid some advice like. not use them simultaneously, thank you. The code bellow suppose to be runnable after copy and paste, if not pardon me for making mistake as I delete few lines to make it cleaner to reproduce the issue.
import SwiftUI
struct ContentView: View {
var body: some View {
ButtonsViewOffset()
}
}
struct ButtonsViewOffset: View {
let location: CGPoint = CGPoint(x: 50, y: 50)
#State private var offset = CGSize.zero
#State private var color = Color.purple
var dragGesture: some Gesture {
DragGesture()
.onChanged{ value in
self.offset = value.translation
print("offset onChange: \(offset)")
}
.onEnded{ _ in
if self.color == Color.purple{
self.color = Color.blue
}
else{
self.color = Color.purple
}
}
}
var body: some View {
VStack {
Text("Watch 3-1")
Text("x: \(self.location.x), y: \(self.location.y)")
}
.background(Color.gray)
.foregroundColor(self.color)
.offset(self.offset)
.position(x: self.location.x, y: self.location.y)
.gesture(dragGesture)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
}
}
}
Your issue has nothing to do with the use of position and offset. They actually both work simultaneously. Position sets the absolute position of the view, where as offset moves it relative to the absolute position. Therefore, you will notice that your view starts at position (50, 50) on the screen, and then you can drag it all around. Once you let go, it stops wherever it was. So far, so good. You then want to move it around again, and it pops back to the original position. The reason it does that is the way you set up location as a let constant. It needs to be state.
The problem stems from the fact that you are adding, without realizing it, the values of offset to position. When you finish your drag, offset retains the last values. However, when you start your next drag, those values start at (0,0) again, therefore the offset is reset to (0,0) and the view moves back to the original position. The key is that you need to use just the position or update the the offset in .onEnded. Don't use both. Here you have a set position, and are not saving the offset. How you handle it depends upon the purpose for which you are moving the view.
First, just use .position():
struct OffsetAndPositionView: View {
#State private var position = CGPoint(x: 50, y: 50)
#State private var color = Color.purple
var dragGesture: some Gesture {
DragGesture()
.onChanged{ value in
position = value.location
print("position onChange: \(position)")
}
.onEnded{ value in
if color == Color.purple{
color = Color.blue
}
else{
color = Color.purple
}
}
}
var body: some View {
Rectangle()
.fill(color)
.frame(width: 30, height: 30)
.position(position)
.gesture(dragGesture)
}
}
Second, just use .offset():
struct ButtonsViewOffset: View {
#State private var savedOffset = CGSize.zero
#State private var dragValue = CGSize.zero
#State private var color = Color.purple
var offset: CGSize {
savedOffset + dragValue
}
var dragGesture: some Gesture {
DragGesture()
.onChanged{ value in
dragValue = value.translation
print("dragValue onChange: \(dragValue)")
}
.onEnded{ value in
savedOffset = savedOffset + value.translation
dragValue = CGSize.zero
if color == Color.purple{
color = Color.blue
}
else{
color = Color.purple
}
}
}
var body: some View {
Rectangle()
.fill(color)
.frame(width: 30, height: 30)
.offset(offset)
.gesture(dragGesture)
}
}
// Convenience operator overload
func + (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
}
So I am trying to make this List or ScrollView in SwiftUI (not fully iOS 14 ready yet, I have to use the old api, so I can't use ScrollViewReader or other fantasy from iOS 14+ SwiftUI api).
The goal is to have only a specific number of rows visible on the view and be able to center the last one.
Images always make it easier to explain. So it should look somewhat like this.
the first two rows have a specific color applied to them, the middle one also but has to be center vertically. then there are eventually 2 more rows under but they are invisible at the moment and will be visible by scrolling down and make them appear.
The closest example i have of this, is the Apple Music Lyrics UI/UX if you are familiar with it.
I am not sure how to approach this here. I thought about create a List that will have a Text with a frame height defined by the height of the view divided by 5. But then I am not sure how to define a specific color for each row depending of which one is it in the view at the moment.
Also, It would be preferable if I can just center the selected row and let the other row have their own sizes without setting one arbitrary.
Banging my head on the walls atm, any help is welcomed! thank you guys.
Edit 1:
Screenshot added as a result from #nicksarno answer. Definitely looking good. The only noted issue atm is that it highlights multiple row with the same color instead of one.
Edit 2:
I did some adjustment to the code #nicksarno published.
let middleScreenPosition = geometryProxy.size.height / 2
return ScrollView {
VStack(alignment: .leading, spacing: 20) {
Spacer()
.frame(height: geometryProxy.size.height * 0.4)
ForEach(playerViewModel.flowReaderFragments, id: \.id) { text in
Text(text.content) // Outside of geometry ready to set the natural size
.opacity(0)
.overlay(
GeometryReader { geo in
let midY = geo.frame(in: .global).midY
Text(text.content) // Actual text
.font(.headline)
.foregroundColor( // Text color
midY > (middleScreenPosition - geo.size.height / 2) && midY < (middleScreenPosition + geo.size.height / 2) ? .white :
midY < (middleScreenPosition - geo.size.height / 2) ? .gray :
.gray
)
.colorMultiply( // Animates better than .foregroundColor animation
midY > (middleScreenPosition - geo.size.height/2) && midY < (middleScreenPosition + geo.size.height/2) ? .white :
midY < (middleScreenPosition - geo.size.height/2) ? .gray :
.clear
)
.animation(.easeInOut)
}
)
}
Spacer()
.frame(height: geometryProxy.size.height * 0.4)
}
.frame(maxWidth: .infinity)
.padding()
}
.background(
Color.black
.edgesIgnoringSafeArea(.all)
)
Now it is closer to what I am looking for. Also, I added some Spacer (not dynamic yet) that will allow to center the text if needed in the middle. Still need to figure how to put the text in the middle when selected one of the element.
Here's how I would do it. First, add a GeometryReader to get the size of the entire screen (screenGeometry). Using that, you can set up the boundaries for your text modifiers (upper/lower). Finally, add a GeoemteryReader behind each of the Text() and (here's the magic) you can use the .frame(in: global) function to find its current location in the global coordinate space. We can then compare the frame coordinates to our upper/lower boundaries.
A couple notes:
The current boundaries are at 40% and 60% of the screen.
I'm currently using the .midY coordinate of the Text geometry, but you can also use .minY or .maxY to get more exact.
The natural behavior of a GeometryReader sizes to the smallest size to fit, so to keep the natural Text sizes, I added a first Text() with 0% opacity (for the frame) and then added the GeometryReader + the actual Text() as an overlay.
Lastly, the .foregroundColor doesn't really animate, so I also added a .colorMultiply on top, which does animate.
Code:
struct ScrollViewPlayground: View {
let texts: [String] = [
"So I am trying to make this List or ScrollView in SwiftUI (not fully iOS 14 ready yet, I have to use the old api, so I can't use ScrollViewReader or other fantasy from iOS 14+ SwiftUI api). The goal is to have only a specific number of rows visible on the view and be able to center the last one.",
"Images always make it easier to explain. So it should look somewhat like this.",
"the first two rows have a specific color applied to them, the middle one also but has to be center vertically. then there are eventually 2 more rows under but they are invisible at the moment and will be visible by scrolling down and make them appear.",
"The closest example i have of this, is the Apple Music Lyrics UI/UX if you are familiar with it.",
"I am not sure how to approach this here. I thought about create a List that will have a Text with a frame height defined by the height of the view divided by 5. But then I am not sure how to define a specific color for each row depending of which one is it in the view at the moment.",
"Also, It would be preferable if I can just center the selected row and let the other row have their own sizes without setting one arbitrary.",
"Banging my head on the walls atm, any help is welcomed! thank you guys."
]
var body: some View {
GeometryReader { screenGeometry in
let lowerBoundary = screenGeometry.size.height * 0.4
let upperBoundary = screenGeometry.size.height * (1.0 - 0.4)
ScrollView {
VStack(alignment: .leading, spacing: 20) {
ForEach(texts, id: \.self) { text in
Text(text) // Outside of geometry ready to set the natural size
.opacity(0)
.overlay(
GeometryReader { geo in
let midY = geo.frame(in: .global).midY
Text(text) // Actual text
.font(.headline)
.foregroundColor( // Text color
midY > lowerBoundary && midY < upperBoundary ? .white :
midY < lowerBoundary ? .gray :
.gray
)
.colorMultiply( // Animates better than .foregroundColor animation
midY > lowerBoundary && midY < upperBoundary ? .white :
midY < lowerBoundary ? .gray :
.clear
)
.animation(.easeInOut)
}
)
}
}
.frame(maxWidth: .infinity)
.padding()
}
.background(
Color.black
.edgesIgnoringSafeArea(.all)
)
}
}
}
struct ScrollViewPlayground_Previews: PreviewProvider {
static var previews: some View {
ScrollViewPlayground()
}
}
I am making a language app and want the correct answer to appear in green once the user taps on it but I am struggling to do so.
This is the part of the code where I want to achieve this behavior.
Grid(viewModel.answers) { answer in
//how can i change the ui of quizView(answer) that is being tapped inside the closure
quizView(answer: answer).onTapGesture {
if self.viewModel.chooseAnswer(answer: answer){
self.dim.toggle()
self.disabled.toggle()
print("a")
}
}
.opacity(self.dim ? 0.4 : 1.0)
.animation(.easeInOut(duration: 1.0))
.disabled(self.disabled)
}
}
.edgesIgnoringSafeArea([.top])
}
}}
struct quizView: View {
var answer: LearnModel.Answer
var body: some View{
GeometryReader { geometry in
ZStack{
answerBubble
Text(self.answer.word.EnglishWord)
.multilineTextAlignment(.center)
.foregroundColor(Color.white)
}
}
}}
var answerBubble: some View {
RoundedRectangle(cornerRadius: 20)
.fill(Color.black)
.shadow(color: Color.black, radius: 20, y: 5)
.opacity(0.2)
.padding()
}
Grid(viewModel.answers) - Creates the Grid and Gridlayout for the answer bubbles.
Screenshot of the UI
Your answerBubble is the view that you're trying to update. So, this view needs to have some type of parameter that changes its fill color.
Let's assume that the background turns green if the user taps the right answer, keeps its black color if it isn't tapped, and turns red otherwise. I would create a stateful list of tapped answers in your main view:
#State private var tappedAnswers = [LearnModel.Answer]()
This will create an empty list of answers that you can keep track of. Once the user taps the quizView, then you should add it to the list if it isn't there already (you could really do this with a Set, but I'm sticking with arrays for its familiarity).
quizView(answer: answer).onTapGesture {
// Add the new answer to the list of tapped answers
if !tappedAnswers.contains(answer) {
tappedAnswers.append(answer)
}
// Do any animation work you need in here
}
I'm not familiar with the rest of your application, but you need to store the correct answer and compare that to the selected answers. We'll call this correctAnswer for now.
Now you can add a function that determines the appropriate fill color for each answerBubble:
func colorFor(answer: LearnModel.Answer, correctAnswer: LearnModel.Answer) -> Color {
if answer == correctAnswer {
// Check for correct answer right away; order matters here.
return Color.green
} else if tappedAnswers.contains(correctAnswer) {
// The user tapped the answer, but it wasn't correct.
return Color.red
} else {
// The user hasn't tapped this answer yet.
return Color.black
}
}
Finally, add a parameter to answerBubble that accepts a fillColor variable that lets you pass in this newly created color method (although you'll need to make this a proper SwiftUI view).
struct AnswerBubble: View {
let fillColor: Color
var body: some View {
RoundedRectangle(cornerRadius: 20)
.fill(fillColor)
.shadow(color: Color.black, radius: 20, y: 5)
.opacity(0.2)
.padding()
}
}
Also make sure that you pass the fillColor you get to quizView since it needs to pass it to answerBubble. Now you can use this inside your ForEach loop. Once you've added the parameters, it should look like:
quizView(
answer: answer,
fillColor: self.colorFor(
answer: answer,
correctAnswer: correctAnswer
)
)
(Also, consider renaming quizView to QuizView since it's not a variable)
I don't know the details of your LearnModel, but you should be able to adapt this as you need.
On occasion, whatever default animation exists in the still limited ScrollView in Swift UI, leads to a "compounding" animation effect.
ScrollView {
Text("Hello")
.animation(
Animation.interpolatingSpring(stiffness: 200, damping: 3)
)
}
This can, sometimes, lead to a much stronger spring effect (with respect to the offset) on initial load as the ScrollView gets rendered.
Is there a way to isolate the spring effect to the offset relative to itself rather than its absolute offset.
As interesting note is that if I turn the ScrollView into VStack this doesn't happen. It seemScrollView has some animation on initial render.
Alright here's a hack for anyone desperate:
struct Hack: View {
#State var show = false
public var body: some View {
ScrollView {
Text("Hello")
.animation(
Animation.interpolatingSpring(stiffness: 200, damping: 3)
)
.opacity(show ? 1 : 0) // this is the hack
.onAppear { self.show.toggle() }
}
}
}
This will disable the egregious (at least in my case) animation on the initial load. This really isn't a good answer nor an insight into whats happening with ScrollView.
Say you have a Circle. How can you change its color when you hover inside the circle?
I tried
struct ContentView: View {
#State var hovered = false
var body: some View {
Circle()
.foregroundColor(hovered ? .purple : .blue)
.onHover { self.hovered = $0 }
}
}
But this causes hovered to be true even when the mouse is outside of the circle (but still inside its bounding box).
I noticed that the .onTapGesture(...) uses the hit testing of the actual shape and not the hit testing of its bounding box.
So how can we have similar hit testing behavior as the tap gesture but for hovering?
The answer depends on the precision you need. The hove in SwiftUI currently just monitor the MouseEnter and MouseExit events, so the working region for a view is the frame which is a Rectangle.
You may build a backgroundView in ZStack which can compose those Rectangle with a customized algorithm. In circle shape, it should be like a matrix with different some small rectangles. One oversimplified example could be like the following.
ZStack{
VStack{
HStack{
Rectangle().frame( width:100, height: 100).offset(x: -50, y: 0)
Rectangle().frame( width:100, height: 100).offset(x: 50, y: 0)
}}.onHover{print($0)}
Rectangle().foregroundColor(hovered ? .purple : .blue).clipShape(Circle())
}