60 lines
1.4 KiB
Swift
60 lines
1.4 KiB
Swift
//
|
|
// DurationPicker.swift
|
|
// WorkoutsPlus
|
|
//
|
|
// Created by Felix Förtsch on 06.10.24.
|
|
//
|
|
|
|
import SwiftUI
|
|
|
|
struct NumbersOnlyTextField: View {
|
|
@Binding var value: Double
|
|
@FocusState private var isFocused: Bool
|
|
|
|
var placeholder = "00:00"
|
|
var formatString = "%.0f"
|
|
|
|
var body: some View {
|
|
VStack {
|
|
HStack {
|
|
ZStack {
|
|
Rectangle()
|
|
.fill(.quaternary)
|
|
.cornerRadius(8)
|
|
.frame(width: placeholderWidth())
|
|
|
|
TextField(placeholder, text: Binding(
|
|
get: { String(format: formatString, value) },
|
|
set: { newValue in
|
|
if let doubleValue = Double(newValue.filter { "0123456789.".contains($0) }) {
|
|
value = doubleValue
|
|
}
|
|
}
|
|
))
|
|
.keyboardType(.decimalPad)
|
|
.frame(width: placeholderWidth())
|
|
.multilineTextAlignment(.center)
|
|
.focused($isFocused)
|
|
}
|
|
}
|
|
.onTapGesture {
|
|
isFocused = false
|
|
}
|
|
}
|
|
}
|
|
|
|
private func placeholderWidth() -> CGFloat {
|
|
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
|
|
let attributes = [NSAttributedString.Key.font: font]
|
|
let size = (placeholder as NSString).size(withAttributes: attributes)
|
|
return size.width + 20
|
|
}
|
|
}
|
|
|
|
#Preview {
|
|
@Previewable @State var value: Double = 0
|
|
List {
|
|
NumbersOnlyTextField(value: $value)
|
|
}
|
|
}
|