Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created January 6, 2022 05:00
Show Gist options
  • Save takoikatakotako/df99952066e24a24173433e84187a86d to your computer and use it in GitHub Desktop.
Save takoikatakotako/df99952066e24a24173433e84187a86d to your computer and use it in GitHub Desktop.
iOS15でPickerを横に並べるとタップ領域が重なってしまう回避策
import SwiftUI
struct ContentView: View {
@State private var hour: Int = 8
@State private var minute: Int = 30
var body: some View {
VStack {
Text("Hour: \(hour), Minute: \(minute)")
TimePicker(hour: $hour, minute: $minute)
.frame(width: 200)
Text("SystemVersion: \(UIDevice.current.systemVersion)")
}
}
}
import SwiftUI
struct TimePicker: UIViewRepresentable {
var hour: Binding<Int>
var minute: Binding<Int>
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<TimePicker>) -> UIPickerView {
let picker = UIPickerView()
picker.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
picker.dataSource = context.coordinator
picker.delegate = context.coordinator
return picker
}
func updateUIView(_ view: UIPickerView, context: UIViewRepresentableContext<TimePicker>) {
view.selectRow(hour.wrappedValue, inComponent: 0, animated: false)
view.selectRow(minute.wrappedValue, inComponent: 1, animated: false)
}
class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
var parent: TimePicker
init(_ pickerView: TimePicker) {
parent = pickerView
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return 24
} else {
return 60
}
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 48
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(format: "%02d", row)
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
parent.hour.wrappedValue = row
} else {
parent.minute.wrappedValue = row
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment