How to get .onHover(...) events for custom Shapes - swift

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())
}

Related

SwiftUI What exactly happens when use .offset and .position Modifier simultaneously on a View, which decides the final location?

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)
}

Single Up/Down Animation on SwiftUI

I'm trying to make an animation where the coin flips and moves up then back down and stops after button click. With this code it moves up and down, but then snaps to the top position after the animation finishes. I know it must be because of the '.offset' but I don't know a way around it. Youtube hasn't been much help.
#State private var isClicked : Bool = false
Image(coins[numbers[0]])
.resizable()
.scaledToFit()
.scaleEffect(0.6)
.rotation3DEffect(isClicked ?
.init(degrees: 1080) : .init(degrees: 0),
axis: (x: 10.0, y: 0.0, z: 0.0))
.animation(Animation.easeInOut.repeatCount(2, autoreverses: true)
.speed(0.5))
.offset(y: isClicked ? -200 : 0)
Button(action: {self.animation()}, label: {
Text("FLIP!")
.aspectRatio(contentMode: .fit)
.foregroundColor(Color.black)
})
func animation() {
self.isClicked.toggle()
}
You should use Animation.easeInOut.repeatCount(3, autoreverses: true, .speed(0.5)
which has repeatCount(3 instead of repeatCount(2. The coin goes up and comes down and thats were it has done its 2 cycles of repeat that you declared. After that, the coin is supposed to be on top, but it has already done its 2 repeat counts so it can't animate itself to the top, and it just goes to the top without any animations. With repeatCount(3, you added one more cycle so the coin has another chance to go back to top and end the animation there.

ScrollView or List, How to make a particular scrollable view (SwiftUI)

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()
}
}

SwiftUI: Synchronise 2 Animation Functions (CAMediaTimingFunction and Animation.timingCurve)

I was using CAMediaTimingFunction (for a window) and Animation.timingCurve (for the content) with the same Bézier curve and time to deal with the resizing. However, there can be a very small time difference and therefore it caused the window to flicker irregularly. Just like this (GitHub repository: http://github.com/toto-minai/DVD-Player-Components ; original design by 7ahang):
Red background indicates the whole window, while green background indicates the content. As you can see, the red background is visible at certain points during the animation, which means that the content is sometimes smaller than the window, so it generates extra small spaces and causes unwanted shaking.
In AppDelegate.swift, I used a custom NSWindow class for the main window and overrode setContentSize():
class AnimatableWindow: NSWindow {
var savedSize: CGSize = .zero
override func setContentSize(_ size: NSSize) {
if size == savedSize { return }
savedSize = size
NSAnimationContext.runAnimationGroup { context in
context.timingFunction = CAMediaTimingFunction(controlPoints: 0, 0, 0.58, 1.00) // Custom Bézier curve
context.duration = animationTime // Custom animation time
animator().setFrame(NSRect(origin: frame.origin, size: size), display: true, animate: true)
}
}
}
In ContentView.swift, the main structure (simplified):
struct ContentView: View {
#State private var showsDrawer: Bool = false
var body: some View {
HStack {
SecondaryAdjusters() // Left panel
HStack {
Drawer() // Size-changing panel
.frame(width: showsDrawer ? 175 : 0, alignment: .trailing)
DrawerBar() // Right bar
.onTapGesture {
withAnimation(Animation.timingCurve(0, 0, 0.58, 1.00, duration: animationTime)) { // The same Bézier curve and animation time
showsDrawer.toggle()
}
}
}
}
}
}
The animated object is the size-changing Drawer() in the middle. I suppose that it is because the different frame rate of two methods. I'm wondering how to synchronise the two functions, and whether there's another way to implement drawer-like View in SwiftUI. You could clone the repository here. Thanks for your patient.

How to emulate the live lyrics animated gradient in swiftui?

It's probably very complicated but would appreciate if someone could lead me in the right direction. I would like to create a flowing gradient animation like the one in the music app. I want to use it to change colours depending on lights for a smart home app. I am familiar with using LinearGradient and animating the start and end points, but this is obviously a lot more complicated but hopefully someone knows what I can do.
I found a MPUGradientView header that includes CAGradientLayer so I'm not sure if its combining gradients to somehow create the effect.
Thanks!
Not exactly reproducing the screenshot you were asking for, but it should get you started.
Inspired from here: https://nerdyak.tech/development/2019/09/30/animating-gradients-swiftui.html
struct MainView: View {
#State var gradient = [Color.red, Color.purple, Color.orange]
#State var startPoint = UnitPoint(x: 0, y: 0)
#State var endPoint = UnitPoint(x: 0, y: 2)
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: self.gradient), startPoint: self.startPoint, endPoint: self.endPoint)
.overlay(
Text("Hello world")
)
}
.edgesIgnoringSafeArea(.all)
.onAppear {
withAnimation(Animation.easeInOut(duration: 6).repeatForever(autoreverses: true)) {
self.startPoint = UnitPoint(x: 1, y: -1)
self.endPoint = UnitPoint(x: 0, y: 1)
}
}
}}
I have ended up getting something quite close in mostly SwiftUI but it requires an image.
Here is a preview of what it looks like:
https://twitter.com/priva2804/status/1284439692352434178?s=21
Here is the gist:
https://gist.github.com/Priva28/22fbae9dbe04a08fadf748793dd23d00