我正在尝试创建一个带有三个相邻的 Picker
视图的页面,如下所示:
我创建了一个名为 CustomPicker
的视图,在该视图中将框架限制为 90 x 240,然后使用 .compositingGroup()
和 .clipped()
使每个 picker 的可选择区域不重叠。
CustomPicker.swift
import SwiftUI
struct CustomPicker: View {
@Binding var selection: Int
let pickerColor: Color
var numbers: some View {
ForEach(0...100, id: \.self) { num in
Text("\(num)")
.bold()
}
}
var stroke: some View {
RoundedRectangle(cornerRadius: 16)
.stroke(lineWidth: 2)
}
var backgroundColor: some View {
pickerColor
.opacity(0.25)
}
var body: some View {
Picker("Numbers", selection: $selection) {
numbers
}
.frame(width: 90, height: 240)
.compositingGroup()
.clipped()
.pickerStyle(.wheel)
.overlay(stroke)
.background(backgroundColor)
.cornerRadius(16)
}
}
ChoicePage.swift
struct ChoicePage: View {
@State var choiceA: Int = 0
@State var choiceB: Int = 0
@State var choiceC: Int = 0
var body: some View {
HStack(spacing: 18) {
CustomPicker(selection: $choiceA, pickerColor: .red)
CustomPicker(selection: $choiceB, pickerColor: .green)
CustomPicker(selection: $choiceC, pickerColor: .blue)
}
}
}
在预览画布和模拟器中测试 CustomPicker
和 ChoicePage
时,它们工作得非常好,但当我尝试在我的物理设备上使用它们(iPhone 8 和 iPhone 13,均运行 iOS 15.1)时,可点击区域会重叠。我尝试了这篇文章、这篇文章以及其他许多解决方案,但似乎没有任何解决方法适用于我。
UIViewRepresentable
解决方案想法:https://dev59.com/MFEG5IYBdhLWcg3wRIid#69842277 - Steve M.contentShape(Rectangle())
,但它没有起作用。我已经回答了原始帖子,并提供了一个来自Steve M的调整后的解决方案。 - Teddy Bersentes