簡體   English   中英

SwiftUI Rectangle 突然變成 RoundedRectangle

[英]SwiftUI Rectangle suddenly transforms into RoundedRectangle

我剛剛開始學習 SwiftUI 並且正在玩視圖和動畫,我想讓 controller 有點像蘋果在控制中心的音量或亮度。 但我發現有趣的小東西,我真的不知道該怎么辦。

struct DragControler: View {
    @GestureState var fillPercentGS : Double = 0.5
    @State var fillPercent = 0.5
    var body: some View {
        ZStack{

            Rectangle()
            GeometryReader { geometry in
                VStack(spacing: 0) {
                    Rectangle().foregroundColor(.red) //these rects
                    Rectangle().foregroundColor(.green).frame(height: geometry.size.height * CGFloat(self.fillPercent))
                }.gesture(DragGesture(coordinateSpace: .local).updating(self.$fillPercentGS, body: { (value, state, transaction) in
                    state =  Double(value.location.y/geometry.size.height)

                }).onChanged({ (value) in
                    self.fillPercent = max(0, min(1 - Double(value.location.y/geometry.size.height), 1))
                }))
            }
            Text("\(fillPercent)").foregroundColor(.white)
            }.cornerRadius(50).aspectRatio(1/4, contentMode: .fit).padding()
    }
}

GIF 當其中一個矩形填滿整個視圖時,它會變成圓形

因此,正如您在 gif 上看到的那樣,當我將它一直拖到頂部或底部時,代碼中明確表示為 Rectangles 的 Rectangles 變為圓角矩形

那么,為什么會這樣呢? 我試圖用 clipShape(RoundedRect(...)) 替換 .cornerRadius() 修飾符,但它沒有幫助。 但我發現它有助於將這些矩形的角半徑顯式設置為零。

Rectangle().cornerRadius(0).foregroundColor(.red)
Rectangle().cornerRadius(0).foregroundColor(...)

我的猜測是 swiftUI 在后台做的有點優化

提前致謝

對我來說它看起來像一個錯誤,但有一個簡單的修復。 只需將綠色矩形的角半徑顯式設置為 0:

Rectangle().foregroundColor(.green).frame(height: geometry.size.height * CGFloat(self.fillPercent)).cornerRadius(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM