作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
将 .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))
}
}
}
最佳答案
在这种情况下,您需要自己调整框架。这需要捕捉框架是什么,然后应用调整。
首先,要捕获现有帧,请创建 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 上的方法。
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/
将 .rotationEffect() 应用于 Text 时,它会按预期旋转文本,但其框架保持不变。当将旋转 View 与非旋转 View (例如 HStack 的 VStack)堆叠时,这会成为一个
我是一名优秀的程序员,十分优秀!