I'm encountering an issue where Text
, depending on its contents, is causing the SwiftUI view to grow larger than the available space rather than wrapping a word to another line. I think it's just a bug (FB11809780) but I'm interested in finding a workaround if possible.
The Text
is within a Form
using the columns
style which will place it in the second column. I embed the ContentView
in a UIHostingController
and give its view
a fixed constant width. In the screenshots you can see depending on the string it can cause the SwiftUI view to grow larger than the containing UIView
- it bleeds out left and right. The second screenshot's text does not cause the issue because it wraps such that the width isn't larger than the available space. It seems to me as if there’s an internal issue calculating how much width is available before it needs to wrap, so it's allowed to be a bit larger than what's actually available.
I've tried adding .fixedSize
to the Text but that didn't impact its behavior.
struct ContentView: View {
@State private var featureEnabled = false
var body: some View {
ScrollView {
VStack(alignment: .leading) {
Toggle(isOn: $featureEnabled) {
Text("Feature")
}
if featureEnabled {
FormView()
}
}
.padding()
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color(UIColor.secondarySystemBackground))
}
}
struct FormView: View {
@State private var selectedOption = 1
var body: some View {
Form {
Picker(selection: $selectedOption, label: Text("Option:")) {
Text("One").tag(1)
Text("Two").tag(2)
Text("Three").tag(3)
}
switch selectedOption {
case 1:
Text("Hellllllo world and all those who inhabit it. Hello universe and all those who inhabit it.")
case 2:
Text("This line of text does not replicate the issue.")
case 3:
Text("This really really really really really really long line of text does not replicate the issue either.")
default:
fatalError()
}
}
.formStyle(.columns)
.font(.system(size: 14))
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let vc = UIHostingController(rootView: ContentView())
addChild(vc)
vc.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(vc.view)
vc.didMove(toParent: self)
let separatorView = UIView()
separatorView.translatesAutoresizingMaskIntoConstraints = false
separatorView.backgroundColor = .label
view.addSubview(separatorView)
NSLayoutConstraint.activate([
vc.view.widthAnchor.constraint(equalToConstant: 320),
vc.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
vc.view.topAnchor.constraint(equalTo: view.topAnchor),
vc.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
separatorView.widthAnchor.constraint(equalToConstant: 1),
separatorView.trailingAnchor.constraint(equalTo: vc.view.leadingAnchor),
separatorView.topAnchor.constraint(equalTo: view.topAnchor),
separatorView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}