我有一个固定的视图RectangleView
,它显示来自外部来源的内容,具有任意的宽度和高度,这意味着直接调整框架不是.frame
修改器的首选.当用户点击按钮旋转这个视图时,视图会按预期旋转,但我希望水平旋转的RectangleView
适合屏幕(同时也保留长宽比),并且不会溢出到显示边界之外.
// Playground
import SwiftUI
import PlaygroundSupport
struct RectangleView: View {
@Binding var rotation: Double
var body: some View {
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 200) // fixed
.rotationEffect(.degrees(rotation))
}
}
struct ContentView: View {
@State public var rotation: Double = 0
var body: some View {
VStack {
RectangleView(rotation: $rotation)
Button(action: {
withAnimation {
rotation += 90
}
}) {
Text("Rotate")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
I had tried using .aspectRatio(contentMode: .fit)
, or a GeometryReader
to make the rectangle fit the screen on 90 or 270 degrees but nothing really works. How to solve this issue?