SwiftUI Scroll/List Scrolling Events - swift

lately I have been trying to create a pull to (refresh, load more) swiftUI Scroll View !!, inspired by https://cocoapods.org/pods/SwiftPullToRefresh
I was struggling to get the offset and the size of the content. but now I am struggling to get the event when the user releases the scroll view to finish the UI.
here is my current code:
struct PullToRefresh2: View {
#State var offset : CGPoint = .zero
#State var contentSize : CGSize = .zero
#State var scrollViewRect : CGRect = .zero
#State var items = (0 ..< 50).map { "Item \($0)" }
#State var isTopRefreshing = false
#State var isBottomRefreshing = false
var top : CGFloat {
return self.offset.y
}
private var bottomLocation : CGFloat {
if contentSize.height >= scrollViewRect.height {
return self.contentSize.height + self.top - self.scrollViewRect.height + 32
}
return top + 32
}
private var shouldTopRefresh : Bool {
return self.top > 80
}
private var shouldBottomRefresh : Bool {
return self.bottomLocation < -80 + 32
}
func watchOffset() -> Binding<CGPoint> {
return .init(get: {
return self.offset
},set: {
print("watched : offset= \($0)")
self.offset = $0
})
}
private func computeOffset() -> CGFloat {
if isTopRefreshing {
print("OFFSET: isTopRefreshing")
return 32
} else if isBottomRefreshing {
if (contentSize.height+32) < scrollViewRect.height {
print("OFFSET: isBottomRefreshing 1")
return top
} else if scrollViewRect.height > contentSize.height {
print("OFFSET: isBottomRefreshing 2")
return 32 - (scrollViewRect.height - contentSize.height)
} else {
print("OFFSET: isBottomRefreshing 3")
return scrollViewRect.height - contentSize.height - 32
}
}
print("OFFSET: fall back->\(top)")
return top
}
func watchScrollViewRect() -> Binding<CGRect> {
return .init(get: {
return self.scrollViewRect
},set: {
print("watched : scrollViewRect= \($0)")
self.scrollViewRect = $0
})
}
func watchContentSize() -> Binding<CGSize> {
return .init(get: {
return self.contentSize
},set: {
print("watched : contentSize= \($0)")
self.contentSize = $0
})
}
func newDragGuesture() -> some Gesture {
return DragGesture()
.onChanged { _ in
print("> drag changed")
}
.onEnded { _ in
DispatchQueue.main.async {
print("> drag ended")
self.isTopRefreshing = self.shouldTopRefresh
self.isBottomRefreshing = self.shouldTopRefresh
withAnimation {
self.offset = CGPoint.init(x: self.offset.x, y: self.computeOffset())
}
}
}
}
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Button(action: { self.presentationMode.wrappedValue.dismiss() }) {
Text("Back")
}
ZStack {
OffsetScrollView(.vertical, showsIndicators: true,
offset: self.watchOffset(),
contentSize: self.watchContentSize(),
scrollViewFrame: self.watchScrollViewRect())
{
VStack {
ForEach(self.items, id: \.self) { item in
HStack {
Text("\(item)")
.font(.system(Font.TextStyle.title))
.fontWeight(.regular)
//.frame(width: geo.size.width)
//.background(Color.blue)
.padding(.horizontal, 8)
Spacer()
}
//.background(Color.red)
.padding(.bottom, 8)
}
}//.background(Color.clear)
}.edgesIgnoringSafeArea(.horizontal)
.background(Color.red)
//.simultaneousGesture(self.newDragGuesture())
VStack {
ArrowShape()
.stroke(style: StrokeStyle.init(lineWidth: 2, lineCap: .round, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0))
.fill(Color.black)
.frame(width: 12, height: 16)
.padding(.all, 2)
//.animation(nil)
.rotationEffect(.degrees(self.shouldTopRefresh ? -180 : 0))
.animation(.linear(duration: 0.2))
.transformEffect(.init(translationX: 0, y: self.top - 32))
.animation(nil)
.opacity(self.isTopRefreshing ? 0 : 1)
Spacer()
ArrowShape()
.stroke(style: StrokeStyle.init(lineWidth: 2, lineCap: .round, lineJoin: .round, miterLimit: 0, dash: [], dashPhase: 0))
.fill(Color.black)
.frame(width: 12, height: 16)
.padding(.all, 2)
//.animation(nil)
.rotationEffect(.degrees(self.shouldBottomRefresh ? 0 : -180))
.animation(.linear(duration: 0.2))
.transformEffect(.init(translationX: 0, y: self.bottomLocation))
.animation(nil)
.opacity(self.isBottomRefreshing ? 0 : 1)
}
// Color.init(.sRGB, white: 0.2, opacity: 0.7)
//
// .simultaneousGesture(self.newDragGuesture())
}
.clipped()
.clipShape(Rectangle())
Text("Offset: \(String(describing: self.offset))")
Text("contentSize: \(String(describing: self.contentSize))")
Text("scrollViewRect: \(String(describing: self.scrollViewRect))")
}
}
}
//https://zacwhite.com/2019/scrollview-content-offsets-swiftui/
public struct OffsetScrollView<Content>: View where Content : View {
/// The content of the scroll view.
public var content: Content
/// The scrollable axes.
///
/// The default is `.vertical`.
public var axes: Axis.Set
/// If true, the scroll view may indicate the scrollable component of
/// the content offset, in a way suitable for the platform.
///
/// The default is `true`.
public var showsIndicators: Bool
/// The initial offset of the view as measured in the global frame
#State private var initialOffset: CGPoint?
/// The offset of the scroll view updated as the scroll view scrolls
#Binding public var scrollViewFrame: CGRect
#Binding public var offset: CGPoint
#Binding public var contentSize: CGSize
public init(_ axes: Axis.Set = .vertical,
showsIndicators: Bool = true,
offset: Binding<CGPoint> = .constant(.zero),
contentSize: Binding<CGSize> = .constant(.zero) ,
scrollViewFrame: Binding<CGRect> = .constant(.zero),
#ViewBuilder content: () -> Content) {
self.axes = axes
self.showsIndicators = showsIndicators
self._offset = offset
self._contentSize = contentSize
self.content = content()
self._scrollViewFrame = scrollViewFrame
}
public var body: some View {
ZStack {
GeometryReader { geometry in
Run {
let frame = geometry.frame(in: .global)
self.$scrollViewFrame.wrappedValue = frame
}
}
ScrollView(axes, showsIndicators: showsIndicators) {
ZStack(alignment: .leading) {
GeometryReader { geometry in
Run {
let frame = geometry.frame(in: .global)
let globalOrigin = frame.origin
self.initialOffset = self.initialOffset ?? globalOrigin
let initialOffset = (self.initialOffset ?? .zero)
let offset = CGPoint(x: globalOrigin.x - initialOffset.x, y: globalOrigin.y - initialOffset.y)
self.$offset.wrappedValue = offset
self.$contentSize.wrappedValue = frame.size
}
}
content
}
}
}
}
}
struct Run: View {
let block: () -> Void
var body: some View {
DispatchQueue.main.async(execute: block)
return AnyView(EmptyView())
}
}
extension CGPoint {
func reScale(from: CGRect, to: CGRect) -> CGPoint {
let x = (self.x - from.origin.x) / from.size.width * to.size.width + to.origin.x
let y = (self.y - from.origin.y) / from.size.height * to.size.height + to.origin.y
return .init(x: x, y: y)
}
func center(from: CGRect, to: CGRect) -> CGPoint {
let x = self.x + (to.size.width - from.size.width) / 2 - from.origin.x + to.origin.x
let y = self.y + (to.size.height - from.size.height) / 2 - from.origin.y + to.origin.y
return .init(x: x, y: y)
}
}
enum ArrowContentMode {
case center
case reScale
}
extension ArrowContentMode {
func transform(point: CGPoint, from: CGRect, to: CGRect) -> CGPoint {
switch self {
case .center:
return point.center(from: from, to: to)
case .reScale:
return point.reScale(from: from, to: to)
}
}
}
struct ArrowShape : Shape {
let contentMode : ArrowContentMode = .center
func path(in rect: CGRect) -> Path {
var path = Path()
let points = [
CGPoint(x: 0, y: 8),
CGPoint(x: 0, y: -8),
CGPoint(x: 0, y: 8),
CGPoint(x: 5.66, y: 2.34),
CGPoint(x: 0, y: 8),
CGPoint(x: -5.66, y: 2.34)
]
let minX = points.min { $0.x < $1.x }?.x ?? 0
let minY = points.min { $0.y < $1.y }?.y ?? 0
let maxX = points.max { $0.x < $1.x }?.x ?? 0
let maxY = points.max { $0.y < $1.y }?.y ?? 0
let fromRect = CGRect.init(x: minX, y: minY, width: maxX-minX, height: maxY-minY)
print("fromRect nx: ",minX,minY,maxX,maxY)
print("fromRect: \(fromRect), toRect: \(rect)")
let transformed = points.map { contentMode.transform(point: $0, from: fromRect, to: rect) }
print("fromRect: transformed=>\(transformed)")
path.move(to: transformed[0])
path.addLine(to: transformed[1])
path.move(to: transformed[2])
path.addLine(to: transformed[3])
path.move(to: transformed[4])
path.addLine(to: transformed[5])
return path
}
}
what I need is a way to tell when the user releases the scrollview, and if the pull to refresh arrow passed the threshold and was rotated, the scroll will move to a certain offset (say 32), and hide the arrow and show an ActivityIndicator.
NOTE: I tried using DragGesture but:
* it wont work on the scroll view
* OR block the scrolling on the scrollview content

You can use Introspect to get the UIScrollView, then from that get the publisher for UIScrollView.contentOffset and UIScrollView.isDragging to get updates on those values which you can use to manipulate your SwiftUI views.
struct Example: View {
#State var isDraggingPublisher = Just(false).eraseToAnyPublisher()
#State var offsetPublisher = Just(.zero).eraseToAnyPublisher()
var body: some View {
...
.introspectScrollView {
self.isDraggingPublisher = $0.publisher(for: \.isDragging).eraseToAnyPublisher()
self.offsetPublisher = $0.publisher(for: \.contentOffset).eraseToAnyPublisher()
}
.onReceive(isDraggingPublisher) {
// do something with isDragging change
}
.onReceive(offsetPublisher) {
// do something with offset change
}
...
}
If you want to look at an example; I use this method to get the offset publisher in my package ScrollViewProxy.

Related

How to implement a slider whose minimum track color is begin from center(value=0) not left in SwiftUI

I want to custom Slider in SwiftUI. Just something like this.
I tried Slider with GeometryReader but it isn't working.
//MARK: Left - Right Balance
GeometryReader { geo in
VStack {
Text("\(String(format: "%.2f", balanceVolume))")
HStack {
Text("L")
Slider(value: $balanceVolume, in: minValue...maxValue, step: 0.1) {editing in
print("editing", editing)
isEditing = editing
if !editing {
player.pan = Float(balanceVolume)
}
}
.tint(.none)
.accentColor(.gray)
Text("R")
}
}
.padding(20)
}
Thank you you all.
I have created a simple custom slider, I hope it helps
Output:
Use:
struct slider: View {
#State var sliderPosition: Float = 50
var body: some View {
SliderView(value: $sliderPosition, bounds: 1...100).padding(.all)
}
}
Code:
struct SliderView: View {
let currentValue: Binding<Float>
let sliderBounds: ClosedRange<Int>
public init(value: Binding<Float>, bounds: ClosedRange<Int>) {
self.currentValue = value
self.sliderBounds = bounds
}
var body: some View {
GeometryReader { geomentry in
sliderView(sliderSize: geomentry.size)
}
}
#ViewBuilder private func sliderView(sliderSize: CGSize) -> some View {
let sliderViewYCenter = sliderSize.height / 2
let sliderViewXCenter = sliderSize.width / 2
ZStack {
RoundedRectangle(cornerRadius: 2)
.fill(Color.gray)
.frame(height: 3)
ZStack {
let sliderBoundDifference = sliderBounds.count
let stepWidthInPixel = CGFloat(sliderSize.width) / CGFloat(sliderBoundDifference)
let thumbLocation = CGFloat(currentValue.wrappedValue) * stepWidthInPixel
// Path between starting point to thumb
lineBetweenThumbs(from: .init(x: sliderViewXCenter, y: sliderViewYCenter), to: .init(x: thumbLocation, y: sliderViewYCenter))
// Thumb Handle
let thumbPoint = CGPoint(x: thumbLocation, y: sliderViewYCenter)
thumbView(position: thumbPoint, value: Float(currentValue.wrappedValue))
.highPriorityGesture(DragGesture().onChanged { dragValue in
let dragLocation = dragValue.location
let xThumbOffset = min(dragLocation.x, sliderSize.width)
let newValue = Float(sliderBounds.lowerBound / sliderBounds.upperBound) + Float(xThumbOffset / stepWidthInPixel)
if newValue > Float(sliderBounds.lowerBound) && newValue < Float(sliderBounds.upperBound + 1) {
currentValue.wrappedValue = newValue
}
})
}
}
}
#ViewBuilder func lineBetweenThumbs(from: CGPoint, to: CGPoint) -> some View {
Path { path in
path.move(to: from)
path.addLine(to: to)
}.stroke(Color.blue, lineWidth: 4)
}
#ViewBuilder func thumbView(position: CGPoint, value: Float) -> some View {
ZStack {
Text(String(round(value)))
.font(.headline)
.offset(y: -20)
Circle()
.frame(width: 24, height: 24)
.foregroundColor(.accentColor)
.shadow(color: Color.black.opacity(0.16), radius: 8, x: 0, y: 2)
.contentShape(Rectangle())
}
.position(x: position.x, y: position.y)
}
}

How to show an overlay on swipe/drag gesture

I want to show an overlay that displays a different image depending on which side the card is dragged towards. I tried setting a default image but that way the image never updated, so I am trying with a string of the imageName instead. I implemented a tinder like swiping already:
class CardViewModel : ObservableObject {
#Published var offset = CGSize.zero
}
struct CardView: View {
#State var offset = CGSize.zero
#StateObject var cardVM = CardViewModel()
#State var imageName = ""
#State var isDragging = false
func swipeCard(width: CGFloat) {
switch width {
case -500...(-150):
offset = CGSize(width: -500, height: 0)
self.imageName = "nope"
case 150...500:
offset = CGSize(width: 500, height: 0)
self.imageName = "bid"
default:
offset = .zero
}
}
var body: some View {
VStack {
}.overlay(
isDragging ? Image(imageName) : Image("")
)
.offset(x: offset.width, y: offset.height * 0.4)
.rotationEffect(.degrees(Double(offset.width / 40)))
.animation(.spring())
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
isDragging = true
} .onEnded { _ in
withAnimation {
swipeCard(width: offset.width)
isDragging = false
}
}
).offset(x: cardVM.offset.width, y: cardVM.offset.height * 0.4)
.rotationEffect(.degrees(Double(cardVM.offset.width / 40)))
.animation(.spring())
}
}

Is there a way to add a flip animation when I tap on my text?

Im trying to make a flash cards program and I can't seem to figure out how to make a flip animation to reveal the corresponding answer. Here is my code:
Text( "\(text)" + " \(X)" + " \(text1)")
.frame(width: 120, height: 300, alignment: .center)
.onTapGesture {
if selection == "Multiply" { text = num1 * num2 clear() }
if selection == "Addition" { text = num1 + num2 clear() }
if selection == "Subtraction" { text = num1 - num2 clear() }
if selection == "Division" { divAnswer = Double(num1 / num2) text = num1 / num2 clear() }
}
(im very new to swifui)
Based on the tutorial from the link in the comment, I set up the following. It created just one card with one exercise, but it shows how it could work. You would have to adjust it to your needs:
//
// CardFlip.swift
// CardFlip
//
// Created by Sebastian Fox on 26.08.22.
//
import SwiftUI
struct ContentView: View {
// For testing, you can setup your exercise here
#State var task: Task = Task(operator1: 5, operator2: 10, operation: .addition)
//MARK: Variables
#State var backDegree = 0.0
#State var frontDegree = -90.0
#State var isFlipped = false
let width : CGFloat = 200
let height : CGFloat = 250
let durationAndDelay : CGFloat = 0.3
//MARK: Flip Card Function
func flipCard () {
isFlipped = !isFlipped
if isFlipped {
withAnimation(.linear(duration: durationAndDelay)) {
backDegree = 90
}
withAnimation(.linear(duration: durationAndDelay).delay(durationAndDelay)){
frontDegree = 0
}
} else {
withAnimation(.linear(duration: durationAndDelay)) {
frontDegree = -90
}
withAnimation(.linear(duration: durationAndDelay).delay(durationAndDelay)){
backDegree = 0
}
}
}
//MARK: View Body
var body: some View {
ZStack {
CardBack(width: width, height: height, degree: $backDegree, task: $task)
CardFront(width: width, height: height, degree: $frontDegree, task: $task)
}.onTapGesture {
flipCard ()
}
}
}
struct CardFront : View {
let width : CGFloat
let height : CGFloat
#Binding var degree : Double
#Binding var task: Task
func calcResult() -> Double {
var result: Double!
switch task.operation {
case .addition: result = task.operator1 + task.operator2
case .substraction: result = task.operator1 - task.operator2
case .mulitply: result = task.operator1 * task.operator2
case .division: result = task.operator1 / task.operator2
}
return result
}
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(.white)
.frame(width: width, height: height)
.shadow(color: .gray, radius: 2, x: 0, y: 0)
.overlay(
Text("\(calcResult(), specifier: "%.2f")"))
}.rotation3DEffect(Angle(degrees: degree), axis: (x: 0, y: 1, z: 0))
}
}
struct CardBack : View {
let width : CGFloat
let height : CGFloat
#Binding var degree : Double
#Binding var task: Task
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(.white)
.frame(width: width, height: height)
.shadow(color: .gray, radius: 2, x: 0, y: 0)
.overlay(
Text("\(String(task.operator1)) \(task.operation.rawValue) \(String(task.operator2))")
)
}.rotation3DEffect(Angle(degrees: degree), axis: (x: 0, y: 1, z: 0))
}
}
struct Task {
var operator1: Double
var operator2: Double
var operation: Operations
}
enum Operations: String, CaseIterable {
case addition = "+"
case division = "/"
case mulitply = "x"
case substraction = "-"
}
Here a gif of how it looks like in the simulator:

How to dynamically change GridItems in LazyVGrid with MagnificationGesture [Zoom In, Out] in SwiftUI?

The idea is to recreate the same photo layout behaviour like in Apple Photo Library when I can zoom in and out with 1, 3 or 5 photos in a row. I'm stack in a half way. For that I use a MagnificationGesture() and based on gesture value I update number of GridItems() in LazyVGrid().
Please let me know how to achieve it. Thanks a lot 🙏
Here's code:
import SwiftUI
struct ContentView: View {
let colors: [Color] = [.red, .purple, .yellow, .green, .blue, .mint, .orange]
#State private var colums = Array(repeating: GridItem(), count: 1)
// #GestureState var magnifyBy: CGFloat = 1.0
#State var magnifyBy: CGFloat = 1.0
#State var lastMagnifyBy: CGFloat = 1.0
let minMagnifyBy = 1.0
let maxMagnifyBy = 5.0
var magnification: some Gesture {
MagnificationGesture()
// .updating($magnifyBy) { (currentState, pastState, trans) in
// pastState = currentState.magnitude
// }
.onChanged { state in
adjustMagnification(from: state)
print("Current State \(state)")
}
.onEnded { state in
adjustMagnification(from: state)
// withAnimation(.spring()) {
// validateMagnificationLimits()
// }
lastMagnifyBy = 1.0
}
}
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: colums) {
ForEach(1..<101) { number in
colors[number % colors.count]
.overlay(Text("\(number)").font(.title2.bold()).foregroundColor(.white))
.frame(height: 100)
}
}
.scaleEffect(magnifyBy)
.gesture(magnification)
.navigationTitle("🧨 Grid")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
withAnimation(.spring(response: 0.8)) {
colums = Array(repeating: .init(), count: colums.count == 5 ? 1 : colums.count % 5 + 2)
}
} label: {
Image(systemName: "square.grid.3x3")
.font(.title2)
.foregroundColor(.primary)
}
}
}
}
}
}
private func adjustMagnification(from state: MagnificationGesture.Value) {
let stepCount = Int(min(max(1, state), 5))
// let delta = state / lastMagnifyBy
// magnifyBy *= delta
withAnimation(.linear) {
colums = Array(repeating: GridItem(), count: stepCount)
}
lastMagnifyBy = state
}
private func getMinMagnificationAllowed() -> CGFloat {
max(magnifyBy, minMagnifyBy)
}
private func getMaxMagnificationAllowed() -> CGFloat {
min(magnifyBy, maxMagnifyBy)
}
private func validateMagnificationLimits() {
magnifyBy = getMinMagnificationAllowed()
magnifyBy = getMaxMagnificationAllowed()
}
}
Here you go. This uses a TrackableScrollView (git link in the code).
I implemented an array of possible zoomStages (cols per row), to make switching between them easier.
Next to dos would be scrolling back to the magnification center, so the same item stays in focus. And maybe an opacity transition in stead of rearranging the Grid. Have fun ;)
import SwiftUI
// https://github.com/maxnatchanon/trackable-scroll-view.git
import SwiftUITrackableScrollView
struct ContentView: View {
let colors: [Color] = [.red, .purple, .yellow, .green, .blue, .mint, .orange]
let zoomStages = [1, 3, 5, 9, 15]
#State private var zoomStageIndex = 0
var colums: [GridItem] { Array(repeating: GridItem(spacing: 0), count: zoomStages[zoomStageIndex]) }
#State var magnifyBy: CGFloat = 1.0
#State private var scrollViewOffset = CGFloat.zero // SwiftUITrackableScrollView: Content offset available to use
var body: some View {
NavigationView {
TrackableScrollView(.vertical, showIndicators: false, contentOffset: $scrollViewOffset) {
LazyVGrid(columns: colums, spacing: 0) {
ForEach(0..<500) { number in
colors[number % colors.count]
.overlay(
Text("\(number)").font(.title2.bold()).foregroundColor(.white)
.minimumScaleFactor(0.1)
)
.aspectRatio(1, contentMode: .fit) // always squares
.id(number)
}
}
.scaleEffect(magnifyBy, anchor: .top)
// offset to correct magnify "center" point
.offset(x: 0, y: (scrollViewOffset + UIScreen.main.bounds.midY) * (1 - magnifyBy) )
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
withAnimation(.spring(response: 0.8)) {
if zoomStageIndex < zoomStages.count-1 {
zoomStageIndex += 1
} else {
zoomStageIndex = 0
}
}
} label: {
Image(systemName: "square.grid.3x3")
.font(.title2)
.foregroundColor(.primary)
}
}
}
.gesture(magnification)
}
.ignoresSafeArea()
}
}
var magnification: some Gesture {
MagnificationGesture()
.onChanged { state in
magnifyBy = state
}
.onEnded { state in
// find predefined zoom(index) that is closest to actual pinch zoom value
let newZoom = Double(zoomStages[zoomStageIndex]) * 1 / state
let newZoomIndex = findClosestZoomIndex(value: newZoom)
// print("***", zoomStages[zoomStageIndex], state, newZoom, newZoomIndex)
withAnimation(.spring(response: 0.8)) {
magnifyBy = 1 // reset scaleEffect
zoomStageIndex = newZoomIndex // set new zoom level
}
}
}
func findClosestZoomIndex(value: Double) -> Int {
let distanceArray = zoomStages.map { abs(Double($0) - value) } // absolute difference between zoom stages and actual pinch zoom
// print("dist:", distanceArray)
return distanceArray.indices.min(by: {distanceArray[$0] < distanceArray[$1]}) ?? 0 // return index of element that is "closest"
}
}

SwiftUI Circular slider issue not displaying the correct stroke when using two control point

I have a circular view with two control knobs and a stroke between the two of them as you can see from the image.
The values are correct but the problem is how could I do display the blue stroke to be the opposite? The user might want the range to be NW, N to NE, and not NE including S to NE but the user needs the ability to pick from both. The code below can be just be pasted in to show the same as the image.
import SwiftUI
struct CircularSliderView: View {
var body: some View {
VStack(){
DirectionView()
Spacer()
}
}
}
struct SwellCircularSliderView_Previews: PreviewProvider {
static var previews: some View {
CircularSliderView()
}
}
struct DirectionView: View {
#State var directionValue: CGFloat = 0.0
#State var secondaryDirectionValue: CGFloat = 0.0
var body: some View {
VStack {
Text("\(directionValue, specifier: "%.0f")° - \(secondaryDirectionValue, specifier: "%.0f")° \(Double().degreesToCompassDirection(degree: Double(directionValue))) - \(Double().degreesToCompassDirection(degree: Double(secondaryDirectionValue)))")
.font(.body)
DirectionControlView(directionValue: $directionValue, secondaryDirectionValue: $secondaryDirectionValue)
.padding(.top, 60)
Spacer()
}//: VSTACK
}
}
struct DirectionControlView: View {
#Binding var directionValue: CGFloat
#State var dirAngleValue: CGFloat = 0.0
#Binding var secondaryDirectionValue: CGFloat
#State var secondaryDirAngleValue: CGFloat = 0.0
let minimumValue: CGFloat = 0
let maximumValue: CGFloat = 360.0
let totalValue: CGFloat = 360.0
let knobRadius: CGFloat = 10.0
let radius: CGFloat = 125.0
private let tickHeight: CGFloat = 8
private let longTickHeight: CGFloat = 14
private let tickWidth: CGFloat = 2
func minimumTrimValue() -> CGFloat{
if directionValue > secondaryDirectionValue {
return secondaryDirectionValue/totalValue
} else {
return directionValue/totalValue
}
}
func maximumTrimValue() -> CGFloat{
if directionValue > secondaryDirectionValue {
return directionValue/totalValue
} else {
return secondaryDirectionValue/totalValue
}
}
var body: some View {
ZStack {
Circle()
.trim(from: minimumTrimValue(), to: maximumTrimValue())
.stroke(
AngularGradient(gradient: Gradient(
colors: [Color.blue.opacity(0.2), Color.blue.opacity(1), Color.blue.opacity(0.2)]),
center: .center,
startAngle: .degrees(Double(secondaryDirectionValue)),
endAngle: .degrees(Double(directionValue))),
style: StrokeStyle(lineWidth: 8, lineCap: .round)
)
.frame(width: radius * 2, height: radius * 2)
.rotationEffect(.degrees(-90))
KnobCircle(radius: knobRadius * 2, padding: 6)
.offset(y: -radius)
.rotationEffect(Angle.degrees(Double(dirAngleValue)))
.shadow(color: Color.black.opacity(0.2), radius: 3, x: -3)
.gesture(DragGesture(minimumDistance: 0.0)
.onChanged({ angleValue in
knobChange(location: angleValue.location)
}))
KnobCircle(radius: knobRadius * 2, padding: 6)
.offset(y: -radius)
.rotationEffect(Angle.degrees(Double(secondaryDirectionValue)))
.shadow(color: Color.black.opacity(0.2), radius: 3, x: -3)
.gesture(DragGesture(minimumDistance: 0.0)
.onChanged({ angleValue in
knobSecondaryChange(location: angleValue.location)
}))
CompassView(count: 240,
longDivider: 15,
longTickHeight: self.longTickHeight,
tickHeight: self.tickHeight,
tickWidth: self.tickWidth,
highlightedColorDivider: 30,
highlightedColor: .blue,
normalColor: .black.opacity(0.2))
.frame(width: 350, height: 350)
CompassNumber(numbers: self.getNumbers(count: 16))
.frame(width: 310, height: 310)
}//: ZSTACK
.onAppear(){
updateInitialValue()
}
}
private func getNumbers(count: Int) -> [Float] {
var numbers: [Float] = []
numbers.append(Float(count) * 30)
for index in 1..<count {
numbers.append(Float(index) * 30)
}
return numbers
}
private func updateInitialValue(){
directionValue = minimumValue
dirAngleValue = CGFloat(directionValue/totalValue) * 360
}
private func knobChange(location: CGPoint) {
let vector = CGVector(dx: location.x, dy: location.y)
let angle = atan2(vector.dy - knobRadius, vector.dx - knobRadius) + .pi/2.0
let fixedAngle = angle < 0.0 ? angle + 2.0 * .pi : angle
let value = fixedAngle / (2.0 * .pi) * totalValue
if value > minimumValue && value < maximumValue {
directionValue = value
dirAngleValue = fixedAngle * 180 / .pi
}
}
private func knobSecondaryChange(location: CGPoint) {
let vector = CGVector(dx: location.x, dy: location.y)
let angle = atan2(vector.dy - knobRadius, vector.dx - knobRadius) + .pi/2.0
let fixedAngle = angle < 0.0 ? angle + 2.0 * .pi : angle
let value = fixedAngle / (2.0 * .pi) * totalValue
if value > minimumValue && value < maximumValue {
secondaryDirectionValue = value
secondaryDirAngleValue = fixedAngle * 180 / .pi
}
}
}
struct KnobCircle: View {
let radius: CGFloat
let padding: CGFloat
var body: some View {
ZStack(){
Circle()
.fill(Color.init(white: 0.96))
.frame(width: radius, height: radius)
.shadow(color: Color.black.opacity(0.1), radius: 10, x: -10, y: 8)
Circle()
.fill(Color.white)
.frame(width: radius - padding, height: radius - padding)
}//: ZSTACK
}
}
struct CompassView: View {
let count: Int
let longDivider: Int
let longTickHeight: CGFloat
let tickHeight: CGFloat
let tickWidth: CGFloat
let highlightedColorDivider: Int
let highlightedColor: Color
let normalColor: Color
var body: some View {
ZStack(){
ForEach(0..<self.count) { index in
let height = (index % self.longDivider == 0) ? self.longTickHeight : self.tickHeight
let color = (index % self.highlightedColorDivider == 0) ? self.highlightedColor : self.normalColor
let degree: Double = Double.pi * 2 / Double(self.count)
TickShape(tickHeight: height)
.stroke(lineWidth: self.tickWidth)
.rotationEffect(.radians(degree * Double(index)))
.foregroundColor(color)
}
}//: ZSTACK
}//: VIEW
}
struct TickShape: Shape {
let tickHeight: CGFloat
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY + self.tickHeight))
return path
}
}
struct CompassNumber: View {
let numbers: [Float]
let direction: [String] = ["N","NE","E","SE","S","SW","W","NW"]
var body: some View {
ZStack(){
ForEach(0..<self.direction.count) { index in
let degree: Double = Double.pi * 2 / Double(self.direction.count)
let itemDegree = degree * Double(index)
VStack(){
Text(self.direction[index])
.font(.footnote)
.rotationEffect(.radians(-itemDegree))
.foregroundColor(.blue)
Spacer()
}//: VSTACK
.rotationEffect(.radians(itemDegree))
}
}//: ZSTACK
}
}
extension Double {
func degreesToCompassDirection(degree: Double) -> String {
switch degree {
case 0..<11.25:
return "N"
case 11.25..<33.75:
return "NNE"
case 33.75..<56.25:
return "NE"
case 56.25..<78.75:
return "ENE"
case 78.75..<101.25:
return "E"
case 101.25..<123.75:
return "ESE"
case 123.75..<146.25:
return "SE"
case 146.25..<168.75:
return "SSE"
case 168.75..<191.25:
return "S"
case 191.25..<213.75:
return "SSW"
case 213.75..<236.25:
return "SW"
case 236.25..<258.75:
return "WSW"
case 258.75..<281.25:
return "W"
case 281.25..<303.75:
return "WNW"
case 303.75..<326.25:
return "NW"
case 326.25..<348.75:
return "NNW"
case 348.75..<360:
return "N"
default:
return "ERROR"
}
}
}
Thanks for your help.
I did a ZStack and displayed Background Stroke. In Case I want to display over the 0 Position (North) I just swapped Background and foreground colors.
var body: some View {
ZStack {
ZStack{
Circle() //Background
.stroke((directionValue < secondaryDirectionValue) ? Color.white : Color.blue)
.frame(width: radius * 2, height: radius * 2)
.rotationEffect(.degrees(-90))
Circle() //Foreground
.trim(from: minimumTrimValue(), to: maximumTrimValue())
.stroke((directionValue < secondaryDirectionValue) ? Color.blue : Color.white)
.frame(width: radius * 2, height: radius * 2)
.rotationEffect(.degrees(-90))
}