Creating a drag handle inside of a SwiftUI view (for draggable windows and such) - swift

I'm trying to learn SwiftUI, and I had a question about how to make a component that has a handle on it which you can use to drag around. There are several tutorials online about how to make a draggable component, but none of them exactly answer the question I have, so I thought I would seek the wisdom of you fine people.
Lets say you have a view that's like a window with a title bar. For simplicity's sake, lets make it like this:
struct WindowView: View {
var body: some View {
VStack(spacing:0) {
Color.red
.frame(height:25)
Color.blue
}
}
}
I.e. the red part at the top is the title bar, and the main body of the component is the blue area. Now, this window view is contained inside another view, and you can drag it around. The way I've read it, you should do something like this (very simplified):
struct ContainerView: View {
#State private var loc = CGPoint(x:150, y:150);
var body: some View {
ZStack {
WindowView()
.frame(width:100, height:100)
.position(loc)
.gesture(DragGesture()
.onChanged { value in
loc = value.location
}
)
}
}
}
and that indeed lets you drag the component around (ignore for now that we're always dragging by the center of the image, it's not really the point):
However, this is not what I want: I don't want you to be able to drag the component around by just dragging inside the window, I only want to drag it around by dragging the red title bar. But the red title-bar is hidden somewhere inside of WindowView. I don't want to move the #State variable containing the position to inside the WindowView, it seems to me much more logical to have that inside ContainerView. But then I need to somehow forward the gesture into the embedded title bar.
I imagine the best way would be for the ContainerView to look something like this:
struct ContainerView: View {
#State private var loc = CGPoint(x:150, y:150);
var body: some View {
ZStack {
WindowView()
.frame(width:100, height:100)
.position(loc)
.titleBarGesture(DragGesture()
.onChanged { value in
loc = value.location
}
)
}
}
}
but I don't know how you would implement that .titleBarGesture in the correct way (or if this is even the proper way to do it. should the gesture be an argument to the WindowView constructor?). Can anyone help me out, give me some pointers?
Thanks in advance!

You can get smooth translation of the window using the offset from the drag, and then disable touch on the background element to prevent content from dragging.
Buttons still work in the content area.
import SwiftUI
struct WindowBar: View {
#Binding var location: CGPoint
var body: some View {
ZStack {
Color.red
.frame(height:25)
Text(String(format: "%.1f: %.1f", location.x, location.y))
}
}
}
struct WindowContent: View {
var body: some View {
ZStack {
Color.blue
.allowsHitTesting(false) // background prevents interaction
Button("Press Me") {
print("Tap")
}
}
}
}
struct WindowView: View, Identifiable {
#State var location: CGPoint // The views current center position
let id = UUID()
/// Keep track of total translation so that we don't jump on finger drag
/// SwiftUI doesn't have an onBegin callback like UIKit's gestures
#State private var startDragLocation = CGPoint.zero
#State private var isBeginDrag = true
init(location: CGPoint = .zero) {
_location = .init(initialValue: location)
}
var body: some View {
VStack(spacing:0) {
WindowBar(location: $location)
WindowContent()
}
.frame(width: 100, height: 100)
.position(location)
.gesture(DragGesture()
.onChanged({ value in
if isBeginDrag {
isBeginDrag = false
startDragLocation = location
}
// In UIKit we can reset translation to zero, but we can't in SwiftUI
// So we do book keeping to track startLocation of gesture and adjust by
// total translation
location = CGPoint(x: startDragLocation.x + value.translation.width,
y: startDragLocation.y + value.translation.height)
})
.onEnded({ value in
isBeginDrag = true /// reset for next drag
}))
}
}
struct ContainerView: View {
#State private var windows = [
WindowView(location: CGPoint(x: 50, y: 100)),
WindowView(location: CGPoint(x: 190, y: 75)),
WindowView(location: CGPoint(x: 250, y: 50))
]
var body: some View {
ZStack {
ForEach(windows) { window in
window
}
}
.frame(width: 600, height: 480)
}
}
struct ContentView: View {
var body: some View {
ContainerView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

You can just use .allowsHitTesting(false) on the blue view, which will ignore the touch gesture on that view. Hence, you can only drag on the red View and still have the DragGesture outside that view.
struct WindowView: View {
var body: some View {
VStack(spacing:0) {
Color.red
.frame(height:25)
Color.blue
.allowsHitTesting(false)
}
}
}

You can wrap the DragGesture into a ViewModifier:
struct MovableByBar: ViewModifier {
static let barHeight: CGFloat = 14
#State private var loc: CGPoint!
#State private var transition: CGSize = .zero
func body(content: Content) -> some View {
if loc == nil { // Get the original position
content.padding(.top, MovableByBar.barHeight)
.overlay {
GeometryReader { geo -> Color in
DispatchQueue.main.async {
let frame = geo.frame(in: .local)
loc = CGPoint(x: frame.midX, y: frame.midY)
}
return Color.clear
}
}
} else {
VStack(spacing: 0) {
Rectangle()
.fill(.secondary)
.frame(height: MovableByBar.barHeight)
.offset(x: transition.width, y: transition.height)
.gesture (
DragGesture()
.onChanged { value in
transition = value.translation
}
.onEnded { value in
loc.x += transition.width
loc.y += transition.height
transition = .zero
}
)
content
.offset(x: transition.width,
y: transition.height)
}
.position(loc)
}
}
}
And use modifier like this:
WindowView()
.modifier(MovableByBar())
.frame(width: 80, height: 60) // `frame()` after it

Related

How to keep the initial animation running while a new one is performed?

I'm having a hard time figuring out this animation thing. The problem is, the .onAppear wobbly animation (which should be forever looped) stops and freezes as soon as the view is dragged (which has another animation so that it smoothly moves towards the drag location).
Is there a way to keep the onAppear animation running independently of the view being dragged around? Important to note is that I do need the position to be dependent on the array (hence drag gesture writes directly to data), and I don't need the wobble (size animation) to be tied to the array at all.
Illustration of the animation freezing on drag (undesirable - would like to circles to still wobble during and after being dragged)
Please see code:
var body: some View {
Circle()
// .resizable()
.frame(width:size.width, height: size.height) //self.size is a state var
.foregroundColor(color)
.position(pos) //pos is a normal var bound to an array row
.gesture(DragGesture()
.onChanged { gesture in
withAnimation(.default) {
ballStorage.balls[numberInArray].position = gesture.location
}
}
.onEnded { gesture in
ballStorage.checkOverlaps(for: numberInArray)
}
) .onAppear {
withAnimation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true)) {
size = CGSize(width: size.width+20, height: size.height+20)
}
}
}
}
You need to separate circle into own view with own animation, then internal animation will be independent of external animation.
Here is a demo of solution on somehow replicated code. Prepared with Xcode 12.1 / iOS 14.1.
struct Ball: Identifiable, Hashable {
let id = UUID()
var position = CGPoint.zero
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
struct BallView: View {
let ball: Ball
var color = Color.blue
#State private var size = CGSize(width: 40, height: 40)
var body: some View {
Circle()
.frame(width:size.width, height: size.height) //self.size is a state var
.animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true), value: size)
.foregroundColor(color)
.onAppear {
size = CGSize(width: size.width+20, height: size.height+20)
}
}
}
struct ContentView: View {
#State private var balls = [Ball(position: CGPoint(x: 100, y: 100)), Ball(position: CGPoint(x: 100, y: 200))]
#State private var off = CGSize.zero
#State private var selected = -1
var body: some View {
ZStack {
ForEach (Array(balls.enumerated()), id: \.1) { i, ball in
BallView(ball: ball)
.offset(x: i == selected ? off.width : 0, y: i == selected ? off.height : 0)
.position(ball.position)
.gesture(DragGesture()
.onChanged { gesture in
self.selected = i
withAnimation(.default) {
self.off = gesture.translation
}
}
.onEnded { gesture in
let pt = balls[i].position
self.balls[i].position = CGPoint(x: pt.x + gesture.translation.width, y: pt.y + gesture.translation.height)
self.off = .zero
self.selected = -1
// ballStorage.checkOverlaps(for: numberInArray)
}
)
}
}
}
}

SwiftUI View struct without reloading

I would like to create a starry background view in SwiftUI that has its stars located randomly using Double.random(), but does not reinitialise them and move them when the parent view reloads its var body.
struct ContentView: View {
#State private var showButton = true
var body: some View {
ZStack {
BackgroundView()
if showButton {
Button("Tap me"){
self.showButton = false
}
}
}
}
}
I define my background view as such.
struct BackgroundView: View {
var body: some View {
ZStack {
GeometryReader { geometry in
Color.black
ForEach(0..<self.getStarAmount(using: geometry), id: \.self){ _ in
Star(using: geometry)
}
LinearGradient(gradient: Gradient(colors: [.purple, .clear]), startPoint: .bottom, endPoint: .top)
.opacity(0.7)
}
}
}
func getStarAmount(using geometry: GeometryProxy) -> Int {
return Int(geometry.size.width*geometry.size.height/100)
}
}
A Star is defined as
struct Star: View {
let pos: CGPoint
#State private var opacity = Double.random(in: 0.05..<0.4)
init(using geometry: GeometryProxy) {
self.pos = CGPoint(x: Double.random(in: 0..<Double(geometry.size.width)), y: Double.random(in: 0..<Double(geometry.size.height)))
}
var body: some View {
Circle()
.foregroundColor(.white)
.frame(width: 2, height: 2)
.scaleEffect(CGFloat(Double.random(in: 0.25...1)))
.position(pos)
.opacity(self.opacity)
.onAppear(){
withAnimation(Animation.linear(duration: 2).delay(Double.random(in: 0..<6)).repeatForever()){
self.opacity = self.opacity+0.5
}
}
}
}
As one can see, a Star heavily relies on random values, for both its animation (to create a 'random' twinkling effect) as well as its position. When the parent view of the BackgroundView, ContentView in this example, gets redrawn however, all Stars get reinitialised, their position values change and they move across the screen. How can this best be prevented?
I have tried several approaches to prevent the positions from being reinitialised. I can create a struct StarCollection as a static let of BackgroundView, but this is quite cumbersome. What is the best way to go about having a View dependent on random values (positions), only determine those positions once?
Furthermore, the rendering is quite slow. I have attempted to call .drawingGroup() on the ForEach, but this then seems to interfere with the animation's opacity interpolation. Is there any viable way to speed up the creation / re-rendering of a view with many Circle() elements?
The slowness coming out from the overcomplicated animations setting in onAppear, you only need the self.opacity state change to initiate the animation, so please move animation out and add to the shape directly.
Circle()
.foregroundColor(.white)
.frame(width: 2, height: 2)
.scaleEffect(CGFloat(Double.random(in: 0.25...1)))
.position(pos)
.opacity(self.opacity)
.animation(Animation.linear(duration: 0.2).delay(Double.random(in: 0..<6)).repeatForever())
.onAppear(){
// withAnimation{ //(Animation.linear(duration: 2).delay(Double.random(in: 0..<6)).repeatForever()){
self.opacity = self.opacity+0.5
// }
}

SwiftUI - how to get coordinate/position of clicked Button

Short version: How do I get the coordinates of a clicked Button in SwiftUI?
I'm looking for something like this (pseudo code) where geometry.x is the position of the clicked button in the current view:
GeometryReader { geometry in
return Button(action: { self.xPos = geometry.x}) {
HStack {
Text("Sausages")
}
}
}
Long version: I'm beginning SwiftUI and Swift so wondering how best to achieve this conceptually.
To give the concrete example I am playing with:
Imagine a tab system where I want to move an underline indicator to the position of a clicked button.
[aside]
There is a answer in this post that visually does what I am going for but it seems rather complicated: How to make view the size of another view in SwiftUI
[/aside]
Here is my outer struct which builds the tab bar and the rectangle (the current indicator) I am trying to size and position:
import SwiftUI
import UIKit
struct TabBar: View {
var tabs:ITabGroup
#State private var selected = "Popular"
#State private var indicatorX: CGFloat = 0
#State private var indicatorWidth: CGFloat = 10
#State private var selectedIndex: Int = 0
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 0) {
ForEach(tabs.tabs) { tab in
EachTab(tab: tab, choice: self.$selected, tabs: self.tabs, x: self.$indicatorX, wid: self.$indicatorWidth)
}
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 40, maxHeight: 40).padding(.leading, 10)
.background(Color(UIColor(hex: "#333333")!))
Rectangle()
.frame(width: indicatorWidth, height: 3 )
.foregroundColor(Color(UIColor(hex: "#1fcf9a")!))
.animation(Animation.spring())
}.frame(height: 43, alignment: .leading)
}
}
Here is my struct that creates each tab item and includes a nested func to get the width of the clicked item:
struct EachTab: View {
// INCOMING!
var tab: ITab
#Binding var choice: String
var tabs: ITabGroup
#Binding var x: CGFloat
#Binding var wid: CGFloat
#State private var labelWidth: CGRect = CGRect()
private func tabWidth(labelText: String, size: CGFloat) -> CGFloat {
let label = UILabel()
label.text = labelText
label.font = label.font.withSize(size)
let labelWidth = label.intrinsicContentSize.width
return labelWidth
}
var body: some View {
Button(action: { self.choice = self.tab.title; self.x = HERE; self.wid = self.tabWidth(labelText: self.choice, size: 13)}) {
HStack {
// Determine Tab colour based on whether selected or default within black or green rab set
if self.choice == self.tab.title {
Text(self.tab.title).foregroundColor(Color(UIColor(hex: "#FFFFFF")!)).font(.system(size: 13)).padding(.trailing, 10).animation(nil)
} else {
Text(self.tab.title).foregroundColor(Color(UIColor(hex: "#dddddd")!)).font(.system(size: 13)).padding(.trailing, 10).animation(nil)
}
}
}
// TODO: remove default transition fade on button click
}
}
Creating a non SwiftUI UILabel to get the width of the Button seems a bit wonky. Is there a better way?
Is there a simple way to get the coordinates of the clicked SwiftUI Button?
You can use a DragGesture recogniser with a minimum drag distance of 0, which provides you the location info. However, if you combine the DragGesture with your button, the drag gesture won't be triggered on normal clicks of the button. It will only be triggered when the drag ends outside of the button.
You can get rid of the button completely, but of course then you lose the default button styling.
The view would look like this in that case:
struct MyView: View {
#State var xPos: CGFloat = 0
var body: some View {
GeometryReader { geometry in
HStack {
Text("Sausages: \(self.xPos)")
}
}.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .global).onEnded { dragGesture in
self.xPos = dragGesture.location.x
})
}
}
The coordinateSpace parameter specifies if you want the touch position in .local or .global space. In the local space, the position is relative to the view that you've attached the gesture to. For example, if I had a Text view in the middle of the screen, my local y position would be almost 0, whereas my global y would be half of the screen height.
This tripped me up a bit, but this example shows the idea:
struct MyView2: View {
#State var localY: CGFloat = 0
#State var globalY: CGFloat = 0
var body: some View {
VStack {
Text("local y: \(self.localY)")
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded { dragGesture in
self.localY = dragGesture.location.y
})
Text("global y: \(self.globalY)")
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .global).onEnded { dragGesture in
self.globalY = dragGesture.location.y
})
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Button(action: { print("Button pressed")}) { Text("Button") }
}.simultaneousGesture(DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onEnded { print("Changed \($0.location)") })
}
}
This solution seems to work, add a simultaneous gesture on Button, unfortunatelly it does not work if the Button is places in a Form
Turns out I solved this problem by adapting the example on https://swiftui-lab.com/communicating-with-the-view-tree-part-2/
The essence of the technique is using anchorPreference which is a means of sending data about one view back up the chain to ancestral views. I couldn't find any docs on this in the Apple world but I can attest that it works.
I'm not adding code here as the reference link also includes explanation that I don't feel qualified to re-iterate here!

SwiftUI Navigation similar to Slack

I am trying to make a navigation UI similar to the Slack app where I have the Home Screen which Overlays the Menu Navigation screen. I created a ViewModifier which makes the Home Screen Draggable. Now I need to add functionality such that when the "Home" is tapped on the blue Menu screen, the white Home View animates back to the center. My idea was to keep track of the NavigationState in a global AppState:
enum NavigationSelection {
case menu
case home
}
final class AppState: ObservableObject {
let objectWillChange = PassthroughSubject<Void, Never>()
#Published var currentNavigationSelection: NavigationSelection = .home
}
Then when the user taps "Home", have it update the AppState's currentNavigationSelection, and have the Draggable view determine its offset based on the currentNavigationSelection. I'm really not sure about this approach and I'm having a tough time thinking about it in the new SwiftUI style. Any suggestions would be much appreciated.
The view hierarchy looks like this:
var body: some View {
ZStack {
Menu()
HomeTabView()
}
}
And the HomeTabView has a draggable ViewModifier applied:
struct Slidable: ViewModifier {
#EnvironmentObject var app: AppState
#State private var viewState = SlidableViewDragState.normal.defaultPosition
#State private var currentPosition: SlidableViewDragState = .normal {
didSet {
self.viewState = self.currentPosition.defaultPosition
}
}
func body(content: Content) -> some View {
return content
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight:
.infinity, alignment: Alignment.topLeading)
.offset(self.viewState)
.animation(.interactiveSpring())
.gesture(
DragGesture()
.onChanged({ (value) in
self.viewState = self.currentPosition.applyXTranslation(x: value.translation.width)
})
.onEnded({ (value) in
if value.translation.width < 0 && self.currentPosition == .normal {
return
}
if abs(value.translation.width) > self.currentPosition.switchThreshold {
self.currentPosition = self.currentPosition.oppositePosition
if self.currentPosition == .menuVisible {
self.app.currentNavigationSelection = .menu
}
} else {
self.viewState = self.currentPosition.defaultPosition
}
})
)
}
}
Moving both views
How do you currently define the positions of both? With my limited experience I would use a ZStack embedding HomeView and MenuView. This way you can move the views around independently.
Then you use a point variable as state, and make the DragGesture set point. Then you determine at the end of the drag what end position point is set to.
point is part of the offset-calculation. You can calculate the menu-offset with .offset(x: point.x) and the home-offset with .offset(x: -Self.maxOffset - Self.minusHomeWidth / 2 + point.x).
minusHomeWidth is the width the menu still shows when you are on the home screen.
Variables defining min and max of the point:
static let minOffset: CGFloat = 0
static let maxOffset: CGFloat = UIScreen.main.bounds.width - Self.minusHomeWidth
static let minusHomeWidth: CGFloat = UIScreen.main.bounds.width / 10
Then you can make it move to the home-view width
Button(action: {
self.point = CGPoint(x: Self.maxOffset, y: 0)
}) { Text("Go to Home") }

Animating to the predictedEndTranslation of a DragGesture on a SwiftUI view

I want to place a view at the predicted location of a DragGesture, that's what I do in my .gestureEnded closure, wrapping the change in a withAnimation block. Yet, when I try it in the live view, the change isn't animated.
Is this a bug of the framework or am I doing something wrong?
struct ContentView: View {
#State var ty: CGFloat = 0
var dragGesture: some Gesture {
DragGesture()
.onChanged { theGesture in
self.ty = theGesture.translation.height
print("Changed")
}
.onEnded { theGesture in
print("Ended")
withAnimation(Animation.easeOut(duration: 3)) {
self.ty = theGesture.predictedEndTranslation.height
}
}
}
var body: some View {
VStack {
ForEach(1 ..< 5) { _ in
Color.red
.frame(minHeight: 20, maxHeight: 100)
.padding(0)
}
}
.transformEffect(.init(translationX: 0, y: ty))
.gesture(dragGesture)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
It seems translateEffect cannot be animated. It kind of makes sense, since CGAffineTransform does not conform to Animatable, so that might be as intended. Fortunately, you can still use .offset(x: 0, y: ty).
Will that work for you?
Note that some animations (like this one), do not work in Xcode Live Preview. You need to run it on a device or the simulator.
An example implementation of the effect for SwiftUI/iOS 13.4, also fixing the view jumping around when dragged repeatedly.
The trick is to use #GestureState to keep track of the gesture in progress and to keep the overall state change separately, applying the changes with the .offset modifier:
struct DragGestureView: View {
#GestureState var dragOffset = CGSize.zero
#State var offset: CGFloat = 0
var dragGesture: some Gesture {
DragGesture()
.updating($dragOffset) { value, state, _ in
state = value.translation
}
.onEnded { gesture in
// keep the offset already moved without animation
self.offset += gesture.translation.height
withAnimation(Animation.easeOut(duration: 3)) {
self.offset += gesture.predictedEndTranslation.height - gesture.translation.height
}
}
}
var body: some View {
VStack {
ForEach(1 ..< 5) { _ in
Color.red
.frame(minHeight: 20, maxHeight: 100)
}
}
.offset(x: 0, y: offset + dragOffset.height)
.gesture(dragGesture)
}
}
struct DragGestureView_Previews: PreviewProvider {
static var previews: some View {
DragGestureView()
}
}
Runnable example via Github: SwiftUIPlayground