如何正确制作此选择器剪辑

问题描述

我通过调用下面的视图在HStack中创建一组并排选择器。每个选取器的“控制”区域比选取器的左侧要宽得多。 “ .clipped()”应该可以解决此问题,但是不起作用。在我开发代码的某个时候,它可以正常工作,但是现在我无法找回它。当我尝试操纵选择器时,可以将最右边的一个移到右边3列的任何位置。左列根本无法操纵。这是怎么回事?

struct SinglePickerView: View {
    @Binding var note: Int
    let notes: [String]
    let width: CGFloat
   
    var body: some View {
        VStack {
            ZStack (alignment: .center) {
                RoundedRectangle(cornerRadius: 5)
                    .fill(Color(red: 192,green: 192,blue: 192))
                    .frame(width: width-10,height: 25)
                Text("\(notes[note])")
                .foregroundColor(.black)
            }

            Picker(selection: $note,label: Text("")) {
                ForEach(0 ..< 72) { index in
                    Text("\(self.notes[index])")
                        .foregroundColor(.white)
                        .tag(index)
               }
            }
            .labelsHidden()
            .frame(width: width)
            .clipped()
        }
    }
}

解决方法

尝试如下移动被剪切的父容器。在Xcode 12 / iOS 14上进行了测试。

struct SinglePickerView: View {
    @Binding var note: Int
    let notes: [String]
    let width: CGFloat

    var body: some View {
        VStack {
            ZStack (alignment: .center) {
                RoundedRectangle(cornerRadius: 5)
                    .fill(Color(red: 192,green: 192,blue: 192))
                    .frame(width: width-10,height: 25)
                Text("\(notes[note])")
                .foregroundColor(.black)
            }

            Picker(selection: $note,label: Text("")) {
                ForEach(0 ..< notes.count,id: \.self) { index in
                    Text("\(self.notes[index])")
                        .foregroundColor(.white)
                        .tag(index)
               }
            }
            .labelsHidden()
        }
        .frame(width: width)
        .contentShape(Rectangle())
        .clipped()
    }
}

struct TestStackOfPickers: View {
    let notes = (1...10).map { String($0) }
    @State var note1 = 1
    @State var note2 = 5
    @State var note3 = 3

    var body: some View {
        HStack {
            SinglePickerView(note: $note1,notes: notes,width: 80).border(Color.red)
            SinglePickerView(note: $note2,width: 80).border(Color.red)
            SinglePickerView(note: $note3,width: 80).border(Color.red)
        }
    }
}
,

我终于找到了真正答案的参考。以下公式至少在iOS 13.6和XCode 11.6中有效。

Picker(selection: $note,label: Text("")) {
    ForEach(0 ..< 72) { index in
        Text("\(self.notes[index])")
            .frame(width: self.width)
            .foregroundColor(.white)
            .tag(index)
       }
}
.labelsHidden()
.frame(width: width)
.compositingGroup() 
.clipped()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...