DynamicScalingView
是一个子视图,有两个按钮,设计为具有相等的宽度和高度,使用preferencekey
问题:当DynamicScalingView
嵌入 NavigationView 时,它不再适应intrinsic
并增加其帧大小。当前没有导航的实现工作正常,但想了解如何在嵌入时解决此问题NavigationView
- 在示例视图中取消注释 NavigationView 以重现问题
DynamicScalingView
应该适应动态字体大小并增加其框架大小,保持按钮之间的宽度和高度相同。
XCode 12.2 和 iOS 14.2
struct SampleView: View {
var body: some View {
GeometryReader { gr in
//NavigationView {
ScrollView {
VStack {
// fills whatever space is left
Spacer()
.foregroundColor(.clear)
// view should fit with intrinsic content size
DynamicScalingView()
.padding(.horizontal, 20)
.border(Color.blue, width: 1)
}
.padding(.bottom, 20)
.border(Color.red, width: 1)
.frame(minHeight: gr.size.height)
.navigationBarHidden(true)
}
// }
}
}
struct DynamicScalingView: View {
@State private var labelHeight = CGFloat.zero
var body: some View {
HStack {
Button(action: {}, label: {
Text("Some Text Some Text Some Text")
.padding(.horizontal, 2)
})
.foregroundColor(Color.white)
.padding(.vertical)
.frame(minWidth: 0, maxWidth: .infinity)
.frame(minHeight: labelHeight)
.background(Color.blue)
.cornerRadius(8)
.fixedSize(horizontal: false, vertical: true)
.background(GeometryReader {
Color.clear
.preference(
key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height
)
})
Button(action: {}, label: {
Text("Some Text")
.padding(.horizontal, 2)
})
.foregroundColor(Color.white)
.padding(.vertical)
.frame(minWidth: 0, maxWidth: .infinity)
.frame(minHeight: labelHeight)
.background(Color.blue)
.cornerRadius(8)
.fixedSize(horizontal: false, vertical: true)
.background(GeometryReader {
Color.clear
.preference(
key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height
)
})
}
.onPreferenceChange(ViewHeightKey.self) {
self.labelHeight = $0
}
}
}
struct ViewHeightKey: PreferenceKey {
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = max(value, nextValue())
}
}
}