TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Day 91: Flashzilla challenge #2

Forums > 100 Days of SwiftUI

I'd be curoius to see other solutions to the challenge #2 (here)[https://www.hackingwithswift.com/books/ios-swiftui/flashzilla-wrap-up]

If you drag a card to the right but not far enough to remove it, then release, you see it turn red as it slides back to the center.

My quick and dirty solution was to set offset = CGSizeMake(0.1, 0.0) instead of offset = .zero in the .onEnded section of the drag gesture. Paul's:

think about the way we set offset back to 0 immediately, even though the card hasn’t animated yet. You might solve this with a ternary within a ternary, but a custom modifier will be cleaner

Suggests there's a ternary way to solve this or a custom modifier. I was unable to understand either of those so am curious if someone else figured it out (particularly the custom modifier route). Thanks,

3      

The issue is not in setting offset = .zero, but in how we approach providing a background view modifier to our RoundedRectangle.

We have a RoundedRectangle that we attach fill modifier to and we give it the color white with some opacity based on the drag offset. So when we drag the card, the white fill becomes transparent allowing us to see anything in the background of that view.

We then also attach a background modifier and that background itself is another RoundedRectangle, but filled in either green or red using the fill modifier: .fill(offset.width > 0 ? .green : .red). Herein lies the problem. When we set offset = .zero, the offset.width is 0, and therefore the fill modifier ternary operator evaluates to .fill(.red). So anytime our offset width is 0, the background of our top level RoundedRectangle is actually a RoundedRectangle(cornerRadius: 25, style: .continuous).fill(.red). You can see this yourself if you just set opacity level the top level RoundedRectangle fill color to 0.

So the solution is to provide a fill color for the background RoundedRectangle based on 3 different potential values for offset.width: when it's greater than 0, when it's less than 0, but also when it's neither of those (ie when it's exactly 0). This can be achieved via a ternary within a ternary or as Paul suggested via a custom modifier to make the code a little less messy.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.