swiftui - SwiftUI layout with left and center views, that avoid overlap
问题描述
Imagine something like a navigation bar — there is an item on the left and in the center. I can create this layout with SwiftUI. (A ZStack
is one way.)
But if the text is too long, I want to avoid overlap by shifting the center item over. I can do this with autolayout by constraining the center item to the center of its parent with one priority, and then constraining them not to overlap with a higher priority.
I keep wishing I had something like constraints in SwiftUI.
Any way to do this layout in SwiftUI?
解决方案
您可以通过结合使用嵌入HStacks
的fixedSized()
、 和layoutPriority()
操作来做到这一点。
源代码
struct CentreTheDarnTextView: View {
var titleText: String
var body: some View {
HStack {
HStack {
Text("I am Left Text")
.fixedSize()
Spacer()
}
Text(titleText)
.layoutPriority(1)
.minimumScaleFactor(0.5)
.lineLimit(1)
.foregroundColor(.red)
HStack {
Spacer()
Text("")
}
}.padding(.all, 8)
}
}
struct CentreTheDarnTextView_Previews: PreviewProvider {
static var previews: some View {
CentreTheDarnTextView(titleText: "I am Centre Text")
.previewLayout(.fixed(width:400, height:44))
CentreTheDarnTextView(titleText: "I am much longer Centre Text")
.previewLayout(.fixed(width:400, height:44))
CentreTheDarnTextView(titleText: "I am rediculously long Centre Text that makes programmers cry")
.previewLayout(.fixed(width:400, height:44))
}
}
.fixedSize()
强制文本不被剪裁,并布局全尺寸。.layoutPriority(1)
非常相似,但您仍然可以应用.minimumScaleFactor()
,.lineLimit()
来处理空间不足的问题。- 那个空
Text("")
就是秘方。
推荐阅读
- java - 如何在junit5中自定义测试并行的逻辑
- azure - 加载缓存时如何对 Azure 云服务 WebRoles 进行负载平衡
- build - 发布时如何定位特定的 .NET Core 运行时?
- kotlin - CollectionsKt.removeAll 是做什么的?
- javascript - 如何指定 Web MIDI 通道?
- vim - 在映射中使用“z=”
- jasmine - 说 Jasmine spy 没有被调用,但我可以看到它被调用
- security - OAuth 2.0 - 为什么同意屏幕不需要客户端密码?
- python - 按列排序和选择,同时在 python 中保留原始索引
- reactjs - history.push(path) 在 react-router-dom v4 中不起作用,在重定向到 404 时使用 redux