I'm having a hard time with resizing a UITextView
generated with code. I'm using swift, but examples in Obj-C are definitely welcomed
. There seems to be two problems here, which are directly related to each-other:
- A constraint is being ignored (Trailing)
- The height calculation is off, probably because the constraint is being ignored.
Here's the code I'm using the generate the UITextView:
if !loaded.biography.isEmpty {
biographyView = UITextView()
biographyView?.translatesAutoresizingMaskIntoConstraints = false
biographyView?.scrollEnabled = false
biographyView?.text = loaded.biography
biographyView?.textColor = UIColor.blackColor()
print("Set text to: " + loaded.biography)
biographyConstraints.append(
NSLayoutConstraint(item: biographyView!, attribute: .LeadingMargin, relatedBy: .Equal, toItem: interactionView, attribute: .LeadingMargin, multiplier: 1, constant: 0)
)
biographyConstraints.append(
NSLayoutConstraint(item: biographyView!, attribute: .TrailingMargin, relatedBy: .Equal, toItem: interactionView, attribute: .TrailingMargin, multiplier: 1, constant: 0)
)
biographyConstraints.append(
NSLayoutConstraint(item: biographyView!, attribute: .Bottom, relatedBy: .Equal, toItem: interactionView, attribute: .Bottom, multiplier: 1, constant: 0)
)
interactionView.addSubview(biographyView!)
}
view.addSubview(interactionView)
NSLayoutConstraint.activateConstraints(interactionConstraints)
if !loaded.biography.isEmpty {
NSLayoutConstraint.activateConstraints(biographyConstraints)
let rect = biographyView?.sizeThatFits((biographyView?.bounds.size)!)
print("Width of bio view is: " + String(biographyView?.bounds.width))
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: biographyView!, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: (rect?.height)!)
])
print("Set height constraint to: " + String(rect?.height))
print("Added interaction & bio & set constraints")
}
The output of this when ran is the following:
Set text to: TESTING TESTING 123 THIS SOME FAKE BIOGRAPHY, I KNOW IT'S NOT MUCH BUT IT'S PLACEHOLDER TEXT, THIS SHOULD BE THE END, OH WAIT, BUT HEY RANDOM EMOJI:
Width of bio view is: Optional(0.0)
Set height constraint to: Optional(30.0)
Added interaction & bio & set constraints
The field is positioned correctly, however the height adjustment is incorrect and the text spans off the screen on the right side. Even though it seems to end at the Trailing margin, the text-field continues to only be a single line of text. I want the text field to adapt to the height of the text.
Can anyone help me figure this out?