Last active
November 23, 2020 14:04
-
-
Save khorbushko/8c81002c5c23226ddc6282efa745f0a3 to your computer and use it in GitHub Desktop.
FatSlider for swiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
struct FatSlider: View { | |
/// value in range 0...1 | |
@Binding var percentage: Float | |
var backgroundTint: Color = Design.Colors.lightGray | |
var pickerTint: Color = Design.Colors.orangeyRed | |
var pickerShadowColor: Color = Design.Colors.black50 | |
var thikness: CGFloat = 4 | |
var isSticky: Bool = true | |
var body: some View { | |
GeometryReader { geometry in | |
ZStack { | |
let centerYPoint = geometry.size.height / 2 | |
Capsule() | |
.foregroundColor(backgroundTint) | |
.frame(height: thikness) | |
.position( | |
x: geometry.size.width / 2, | |
y: centerYPoint | |
) | |
let heightOfPicker: CGFloat = thikness * 10 | |
let widthOfPicker: CGFloat = geometry.size.width / 3 | |
let currentXPositionOfPicker: CGFloat = | |
geometry.size.width * CGFloat(percentage) | |
let normalizedPosX = min( | |
geometry.size.width - widthOfPicker / 2, | |
max(widthOfPicker / 2, currentXPositionOfPicker) | |
) | |
Capsule() | |
.foregroundColor(pickerTint) | |
.frame(width: widthOfPicker, height: heightOfPicker) | |
.position( | |
x: normalizedPosX, | |
y: centerYPoint | |
) | |
.shadow( | |
color: pickerShadowColor, | |
radius: 2.0, | |
x: 2, | |
y: 2 | |
) | |
.gesture( | |
DragGesture(minimumDistance: 0) | |
.onChanged({ (value) in | |
let activeWidth = geometry.size.width - widthOfPicker | |
let pointX = | |
min( | |
geometry.size.width - widthOfPicker, | |
max(0, value.location.x - widthOfPicker / 2) | |
) | |
percentage = Float(pointX / activeWidth) | |
}) | |
.onEnded({ (value) in | |
if isSticky { | |
withAnimation { | |
percentage = 0 | |
} | |
} | |
}) | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment