SwiftUI.rotationEffect()成帧和偏移
将.rotationEffect()应用于文本时,它会按预期旋转文本,但其框架保持不变。在将旋转视图与非旋转视图(例如使用HStack的VStack)堆叠时,这会成为一个问题,导致它们重叠 我最初认为rotationEffect会简单地将文本的框架更新为垂直,但事实并非如此 我尝试过手动设置框架大小和(如果需要,偏移)文本,哪种方式有效,但我不喜欢这种解决方案,因为它需要猜测和检查文本将出现的位置、框架的大小等 这就是旋转文本的方式,还是有更优雅的解决方案SwiftUI.rotationEffect()成帧和偏移,swift,swiftui,Swift,Swiftui,将.rotationEffect()应用于文本时,它会按预期旋转文本,但其框架保持不变。在将旋转视图与非旋转视图(例如使用HStack的VStack)堆叠时,这会成为一个问题,导致它们重叠 我最初认为rotationEffect会简单地将文本的框架更新为垂直,但事实并非如此 我尝试过手动设置框架大小和(如果需要,偏移)文本,哪种方式有效,但我不喜欢这种解决方案,因为它需要猜测和检查文本将出现的位置、框架的大小等 这就是旋转文本的方式,还是有更优雅的解决方案 struct TextAloneVie
struct TextAloneView: View {
var body: some View {
VStack {
Text("Horizontal text")
Text("Vertical text").rotationEffect(.degrees(-90))
}
}
}
RotationEffect接受第二个参数,即锚点,如果忽略它,则默认为.center 请尝试以下方法:
.rotationEffect(.degrees(-90), anchor: .bottomTrailing)
在这种情况下,您需要自己调整框架。这需要捕获帧的内容,然后应用调整 首先,要捕获现有框架,请创建,这是一个用于将数据从子视图传递给其父视图的系统:
private struct SizeKey: PreferenceKey {
static let defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
extension View {
func captureSize(in binding: Binding<CGSize>) -> some View {
overlay(GeometryReader { proxy in
Color.clear.preference(key: SizeKey.self, value: proxy.size)
})
.onPreferenceChange(SizeKey.self) { size in binding.wrappedValue = size }
}
}
为方便起见,对其进行了扩展:
extension View {
func rotated(_ angle: Angle = .degrees(-90)) -> some View {
Rotated(self, angle: angle)
}
}
现在,您的代码应该可以按预期工作:
struct TextAloneView: View {
var body: some View {
VStack {
Text("Horizontal text")
Text("Vertical text").rotated()
}
}
}
.rotationEffect()保持帧不变有什么原因吗?例如,如果我将旋转后的文本夹在两条水平文本行之间:上面和下面,为什么VStack会将文本放在水平位置?
struct TextAloneView: View {
var body: some View {
VStack {
Text("Horizontal text")
Text("Vertical text").rotated()
}
}
}