SwiftUI .rotationEffect() 框架和偏移

EZh*_*u00 15 swift swiftui

将 .rotationEffect() 应用于 Text 时,它会按预期旋转文本,但其框架保持不变。当将旋转视图与非旋转视图(例如 HStack 的 VStack)堆叠时,这会成为一个问题,导致它们重叠。

我最初认为 rotationEffect 会简单地将 Text 的框架更新为垂直,但事实并非如此。

我试过手动设置框架大小和(如果需要,偏移)文本,这有点工作,但我不喜欢这个解决方案,因为它需要一些猜测和检查文本将出现的位置,制作多大框架等。

这就是旋转文本的完成方式,还是有更优雅的解决方案?

struct TextAloneView: View {

    var body: some View {
        VStack {
            Text("Horizontal text")
            Text("Vertical text").rotationEffect(.degrees(-90))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

重叠文本

Rob*_*ier 17

在这种情况下,您需要自己调整框架。这需要捕捉框架是什么,然后应用调整。

首先,要捕获现有框架,请创建一个首选项,这是一个将数据从子视图传递给其父视图的系统:

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 }
    }
}
Run Code Online (Sandbox Code Playgroud)

.captureSize(in: $binding)在视图上创建了一个新方法。

使用它,我们可以创建一种旋转其框架的新视图:

struct Rotated<Rotated: View>: View {
    var view: Rotated
    var angle: Angle

    init(_ view: Rotated, angle: Angle = .degrees(-90)) {
        self.view = view
        self.angle = angle
    }

    @State private var size: CGSize = .zero

    var body: some View {
        // Rotate the frame, and compute the smallest integral frame that contains it
        let newFrame = CGRect(origin: .zero, size: size)
            .offsetBy(dx: -size.width/2, dy: -size.height/2)
            .applying(.init(rotationAngle: CGFloat(angle.radians)))
            .integral

        return view
            .fixedSize()                    // Don't change the view's ideal frame
            .captureSize(in: $size)         // Capture the size of the view's ideal frame
            .rotationEffect(angle)          // Rotate the view
            .frame(width: newFrame.width,   // And apply the new frame
                   height: newFrame.height)
    }
}
Run Code Online (Sandbox Code Playgroud)

为方便起见,应用它的扩展:

extension View {
    func rotated(_ angle: Angle = .degrees(-90)) -> some View {
        Rotated(self, angle: angle)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您的代码应该按您的预期工作:

struct TextAloneView: View {

    var body: some View {
        VStack {
            Text("Horizontal text")
            Text("Vertical text").rotated()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)