Как вы можете видеть на видео, сначала он находится немного левее центра, затем перемещается к центру и, наконец, в конце смещается вправо.
VideoLink: Ссылка
Изменить: Я получил ответ благодаря @BenzyNeez.
Просто замените .position на приведенный ниже .offset
.offset(
x: CGFloat(value - range.lowerBound) * (proxy[anchor].size.width - proxy[anchor].size.height) / CGFloat(range.upperBound - range.lowerBound),
y: proxy[anchor].minY - size.height - 10
)
struct ContentView: View {
@State private var value: Float = .zero
@State private var isEditing = false
@State private var size: CGSize = .zero
private let range: ClosedRange = 0...10
var body: some View {
Slider(value: $value, in: range) { value in
isEditing = value
}
.anchorPreference(key: OverlayPreferenceKey.self, value: .bounds) { $0 }
.padding(.horizontal)
.tint(.red)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.overlayPreferenceValue(OverlayPreferenceKey.self) { anchor in
if isEditing, let anchor {
GeometryReader { proxy in
Text(value, format: .number.precision(.fractionLength(1)))
.foregroundStyle(.black)
.font(.body.monospacedDigit())
.padding(.vertical, 12)
.padding(.horizontal, 20)
.background(.white)
.clipShape(.capsule)
.overlay {
Capsule()
.stroke(.black.opacity(0.5), lineWidth: 0.5)
}
.background {
GeometryReader { proxy in
Color.clear
.onChange(of: proxy.size, initial: true) { old, new in
size = new
}
}
}
.position(
x: proxy[anchor].minX + (CGFloat((value - range.lowerBound) / (range.upperBound - range.lowerBound))) * proxy[anchor].width,
y: proxy[anchor].minY - size.height / 2 - 10
)
}
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... lignment-i
Мобильная версия