带有覆盖的 SwiftUI 中的文本溢出到矩形边界之外
Text spills outside of boundary of Rectangle in SwiftUI with overlay
我希望蓝色矩形中的文本 1 和文本 2 位于 Rectangle
的边界内,但在使用覆盖时,它似乎超出了给定边界。如何解决这个问题?
我也试过 ZStack
但结果一样。
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
ZStack {
Rectangle()
.stroke(lineWidth: 1)
.frame(width: 1, height: 55)
Rectangle()
.stroke(lineWidth: 10)
.cornerRadius(15)
.foregroundColor(Color.blue)
.frame(width: .infinity, height: 60)
.padding()
}
.overlay(
HStack {
Text("Text 1")
Spacer()
Text("Text 2")
}
)
}
}
}
你需要在不同的地方放置叠加层(修饰符的顺序很重要!),比如
var body: some View {
VStack {
ZStack {
Rectangle()
.stroke(lineWidth: 1)
.frame(width: 1, height: 55)
Rectangle()
.stroke(lineWidth: 10)
.cornerRadius(15)
.foregroundColor(Color.blue)
.overlay(
HStack { // << here !!
Text("Text 1")
Spacer()
Text("Text 2")
}
.padding(.horizontal)
)
.frame(width: .infinity, height: 60)
.padding()
}
}
}
测试 Xcode 13 / iOS 15
我希望蓝色矩形中的文本 1 和文本 2 位于 Rectangle
的边界内,但在使用覆盖时,它似乎超出了给定边界。如何解决这个问题?
我也试过 ZStack
但结果一样。
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
ZStack {
Rectangle()
.stroke(lineWidth: 1)
.frame(width: 1, height: 55)
Rectangle()
.stroke(lineWidth: 10)
.cornerRadius(15)
.foregroundColor(Color.blue)
.frame(width: .infinity, height: 60)
.padding()
}
.overlay(
HStack {
Text("Text 1")
Spacer()
Text("Text 2")
}
)
}
}
}
你需要在不同的地方放置叠加层(修饰符的顺序很重要!),比如
var body: some View {
VStack {
ZStack {
Rectangle()
.stroke(lineWidth: 1)
.frame(width: 1, height: 55)
Rectangle()
.stroke(lineWidth: 10)
.cornerRadius(15)
.foregroundColor(Color.blue)
.overlay(
HStack { // << here !!
Text("Text 1")
Spacer()
Text("Text 2")
}
.padding(.horizontal)
)
.frame(width: .infinity, height: 60)
.padding()
}
}
}
测试 Xcode 13 / iOS 15