How do you do “wrap_content” (Android XML syntax) in iOS Swift

i0S Swift Issue

Question or problem with Swift language programming:

I am an Android developer trying to learn iOS development in Swift. I was wondering how you achieve “wrap_content” in Xcode. Any ideas? What are the variables to change in the attribute inspector?

How to solve the problem:

Solution 1:

The Android docs state that wrap_content:


tells your view to size itself to the dimensions required by its content.

This sounds analogous to what Apple calls the intrinsic content size. They detail how to configure it in the attribute inspector here.


To override the intrinsic content size of a UIView (such as a UILabel or a UIButton), you would simply have to override UIView‘s intrinsicContentSize() method.

Solution 2:

Try following code that fits textView’s frame according to it’s contained data-

let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;

Solution 3:

u can do this in storyboard

  1. select the UIView*
  2. in Attribute Inspector select Line Breaks
  3. choose Word Wrap

be sure no other constraint defined for the view which limit the width!

Solution 4:

You can use a trick with constraints to achieve wrap-content. For example :

let maximumWidth = frame / 4  //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true

The “maximumWidth” depends on your UI and your design and you can change it.

Also, you should set “lineBreakMode” in StoryBoard or in code like :

yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView

Hope this helps!