gpt4 book ai didi

SwiftUI .rotationEffect() 框架和偏移

转载 作者:行者123 更新时间:2023-12-03 09:16:38 25 4
gpt4 key购买 nike

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

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

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

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

struct TextAloneView: View {

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

Overlapping Text

最佳答案

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

首先,要捕获现有帧,请创建 a preference ,这是一个将数据从 subview 传递给父 View 的系统:

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 }
}
}

这将创建一个新的 .captureSize(in: $binding) View 上的方法。

使用它,我们可以创建一种旋转其框架的新 View :
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)
}
}

为方便起见,应用它的扩展:
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()
}
}
}

关于SwiftUI .rotationEffect() 框架和偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com