一个 SwiftUI 滑块组件,它沿着任何自定义路径,实现独特且引人入胜的用户交互。

此示例使用 Path(ellipseIn: CGRect)
初始化器快速创建一个路径。该 View 持有滑块 value
的 @State
和 pathPoint
,后者是“拇指”指示器的位置。
import SwiftUI
import PathSlider
struct EllipseView: View {
@State var pathPoint: CGPoint = .zero
@State var value: Float = 0.5
let path = Path(
ellipseIn: CGRect(origin: .init(x: 0, y: 100),
size: .init(width: 300, height: 160)))
var body: some View {
VStack(alignment: .center) {
PathSlider(
path: path,
value: $value,
in: 0...1,
pathPoint: $pathPoint
) {
// Draw indicator view
Circle()
.stroke(.blue, lineWidth: 2.0)
.fill(.blue.gradient)
.frame(
width: 20,
height: 20,
alignment: .center
)
} track: { path in
// Draw path and/or accessory views
path
.stroke(
Color.primary.opacity(0.2),
lineWidth: 2
)
}
}
}
}
|
|
此示例使用 SwiftUI Shape
和包含的 slider
扩展方法来利用 Shape 提供的 Path。 在这里,我们通过使用 Circle 和 RoundedRectangle 渲染了两个 PathSlider
组件。 请注意,RoundedRectangle shape 使用 trim
方法进行了修改,使其具有开放的顶端。
import SwiftUI
import PathSlider
struct ShapeView: View {
@State var dragPoint: CGPoint = .zero
@State var value: Float = 0.5
var body: some View {
VStack {
Circle()
.slider(value: $value, in: 0...1, pathPoint: $dragPoint) {
Circle()
.stroke(.blue, lineWidth: 2.0)
.fill(.blue.gradient)
.frame(width: 20, height: 20, alignment: .center)
} track: { path in
path
.stroke(Color.black.opacity(0.6), lineWidth: 2)
}
.frame(maxWidth: 300, maxHeight: 280)
.padding()
RoundedRectangle(cornerRadius: 15)
.trim(from: 0, to: 0.5)
.slider(value: $value, in: 0...1) {
Circle()
.stroke(.blue, lineWidth: 2.0)
.fill(.blue.gradient)
.frame(width: 20, height: 20, alignment: .center)
} track: { path in
path
.stroke(Color.black.opacity(0.6), lineWidth: 2)
}
.frame(maxWidth: 300, maxHeight: 280)
.padding()
}
}
}
|
|
在 Examples
目录中包含 Examples.xcodeproj
。 请查看此项目,以更具交互性的方式查看上述用法示例。 如果您有任何有趣的示例想要分享,欢迎提交 pull request!