在swiftUI中调整VStack的框架大小

时间:2020-03-02 16:14:35

标签: ios swift xcode swiftui

在Card结构中将框架的大小调整为vstack中屏幕的整个宽度时遇到麻烦。

我该怎么做才能使卡片变大,以便可以根据屏幕大小进行调整?

tony@ubuntu:~/Documents/google_maps$ python3 websockets.py 
Testing
blah
Testing
blah

2 个答案:

答案 0 :(得分:2)

发生这种情况是因为您在错误的视图上使用GeometryReader,请尝试使用此方法并检查结果:

import SwiftUI

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal, showsIndicators: false){
                HStack{
                    ForEach(0..<14){ _ in
                        Card()
                            .frame(width: geometry.size.width, height: geometry.size.height/1.5)
                            .padding(.leading)
                        }
                }
            }
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct Card: View {
    var body: some View {
        GeometryReader{r in
            VStack(alignment: .leading){
                Color.red
            }.cornerRadius(20)
                .padding(.leading)
        }
    }
}

答案 1 :(得分:2)

欢迎来到Stackoverflow!

我想您希望卡片的宽度等于屏幕尺寸,并希望它像在屏幕截图中一样位于scrollView中。如果是这样,请继续阅读...

您在正确的道路上。但是,最好在创建卡片时将卡片取景,而不是在设置卡片body时放置卡片。

struct ContentView: View {
    var body: some View {
        VStack{
            GeometryReader{r in
                ScrollView(.horizontal, showsIndicators: false){
                    HStack{
                        ForEach(0..<14) { i in
                            Card(color: Color.init(UIColor.random())).frame(width: r.size.width, height: r.size.height/1.5, alignment: .center)
                        }
                    }
                }
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct Card: View {
    var color: Color
    var body: some View {
        GeometryReader{r in
            self.color
        }
    }
}

要获得红利,让我们使用随机颜色。

extension UIColor {
    static func random() -> UIColor {

        func random() -> CGFloat { return .random(in:0...1) }

        return UIColor(red:   random(),
                       green: random(),
                       blue:  random(),
                       alpha: 1.0)
    }
}

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html