首页 > 解决方案 > 如何在视图中隐藏超大的背景视图?

问题描述

我有一个简单的矩形,我在它的背景中放了一个数字的 VStack,你可以在代码和图片中看到它!问题是 VStack 比 Rectangle 高,因为它超出了 Rectangle,我希望隐藏额外的部分,我该如何解决?

    struct ContentView: View {
    
    let arrayOfHours: [Int] = Array(0...23)
    
    var body: some View {

            Rectangle()
                .fill(Color.black.opacity(0.25))
                .frame(height: 200, alignment: .center)
                .padding()
                .background(
                
                    VStack(alignment: .center, spacing: 4) {
                        
                        ForEach (arrayOfHours.indices, id: \.self) { index in
                            
                            Text(arrayOfHours[index].description)
                                .font(Font.body.bold())
                            
                        }
                    }
                    .background(Color.yellow)

                )

    }
}

在此处输入图像描述

标签: swiftui

解决方案


如果我正确理解了你的描述,你需要clipped,比如

演示

    struct ContentView: View {
    
    let arrayOfHours: [Int] = Array(0...23)
    
    var body: some View {

            Rectangle()
                .fill(Color.black.opacity(0.25))
                .frame(height: 200, alignment: .center)
                .background(
                
                    VStack(alignment: .center, spacing: 4) {
                        
                        ForEach (arrayOfHours.indices, id: \.self) { index in
                            
                            Text(arrayOfHours[index].description)
                                .font(Font.body.bold())
                            
                        }
                    }
                    .background(Color.yellow)

                )
                .clipped()        // << here !!
                .padding()        // should be moved here !!
    }
}

推荐阅读