Get UITextView dynamic height with auto layout after setting text - ios

I have a UITextView not scrollable with auto layout set by interface builder, and the text increase or decrease dynamically with no problem, but i want know what is the new UITextView height after setting text, i'm trying to do this:
NSLog(#"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
NSLog(#"text after: %.2f",self.myText.frame.size.height);
this is the result:
text before: 47.50
text after: 47.50
the text is increased in the view when i run it, but the size is the same, how i can get the real height after setting text?

All you have to do is:
set up all your constraints except the height one AND
set textView's scrollEnabled property to NO
The last part is what does the trick.
Your text view will size automatically depending on its text value.

If you prefer to do it all by auto layout:
In Size Inspector:
Set Content Compression Resistance Priority Vertical to 1000.
Lower the priority of constraint height for your UITextView. Just make it less than 1000.
In Attributes Inspector:
Uncheck Scrolling Enabled.

I have used the code given on following link AutoLayout with Dynamic UITextView height and it worked for me :)

This should work:
NSLog(#"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
[self.myText layoutIfNeeded]; // <--- Add this
NSLog(#"text after: %.2f",self.myText.frame.size.height);
Here's an example implementation on my Github: https://github.com/guillaume-algis/SO-27060338

Swift 3.0
textView.isScrollEnabled = false
This allow AutoLayout to do its job.

Use below code:
Objective-C Code
[textView setScrollEnabled:NO];
Swift Code
textView.isScrollEnabled = false

Just after changing the text call
[self.myText sizeToFit];

Unlike UILabel, UITextView's has no intrinsic size property. So how I did it was set up the UITextView's height constraint, hook it via IBOutlet, and change its value in textViewDidChange or when text changes.
#IBOutlet weak var textViewHeight: NSLayoutConstraint!
func textViewDidChange(textView: UITextView) {
// dynamic height adjustments
var height = ceil(textView.contentSize.height) // ceil to avoid decimal
if height != textViewHeight.constant { // set when height changed
textViewHeight.constant = height
textView.setContentOffset(CGPointZero, animated: false) // scroll to top to avoid "wrong contentOffset" artefact when line count changes
}
}

- (void)textViewDidChange:(UITextView *)textView
{
UIFont *myFont = [UIFont systemFontOfSize:14];
CGSize size = [self sizeOfText:textView.text widthOfTextView:TextviewWidth withFont:myFont];
NSLog(#"Height : %f", size.height);
}
-(CGSize)sizeOfText:(NSString *)textToMesure widthOfTextView:(CGFloat)width withFont:(UIFont*)font
{
CGSize ts = [textToMesure sizeWithFont:font constrainedToSize:CGSizeMake(width-20.0, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
return ts;
}

select textview and uncheck "Scrolling enabled"
select textview from top menu "Editor > size to fit content"
select the view below it, set its top constraints with the textview bottom to whatever margin you want, then go to "Size Inspector",double click or edit the constraint you just added, and set the "Relation" to "Greater than or Equal"

Yet another approach is to use
myTextView.textContainer.heightTracksTextView = true
Which allows scroll to be enabled

Well, I haven't converted this code into swift4 syntax, but the logic will remain the same. This is an extension method for Xamarin.ios(C#).
public static nfloat GetEstimateHeight(this UITextView textView, UIView View)
{
var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
var estimatedSize = textView.SizeThatFits(size);
return estimatedSize.Height;
}
The logic here that will work for swift is
var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
var estimatedSize = textView.SizeThatFits(size);
var textViewFinalHeight = estimatedSize.Height;

Just an addition as per #Pavel Gurov's answer. If you already set up your height constraint, simply make it inactive. Also worth to call .sizeToFit() afterwards to make sure resize action is performed.
theTextViewHeightConstraint.isActive = false
theTextView.isScrollEnabled = false
theTextView.text = "some text"
theTextView.sizeToFit()

the textview height increase by using pure swift code design. I am just do coding part only.
I take this idea from
https://stackoverflow.com/a/45071002/9110213
First thing create the textView
import UIKit
class TextFieldCell: UITableViewCell {
lazy var btnEdit: UIButton! = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(self.actionEdit(_:)), for: .touchUpInside)
button.setTitle("Edit", for: .normal)
button.titleLabel?.font = UIFont(name: "ProximaNova-Medium", size: 18)
button.setTitleColor( UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1), for: .normal)
button.titleLabel?.textAlignment = .left
return button
}()
lazy var separatorView: UIView! = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var textView: UITextView! = {
let textView = UITextView.init(frame: .zero)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
textView.isScrollEnabled = false
return textView
}()
lazy var titleLabel: UILabel! = {
let label = UILabel(frame: CGRect(x: 27, y: 318, width: 27, height: 12))
label.text = "Name"
label.font = UIFont(name: "ProximaNova-Medium", size: 10)
label.textColor = UIColor(red: 0.61, green: 0.61, blue: 0.61, alpha: 1)
label.textAlignment = .left
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
deinit {
self.titleLabel = nil
self.textView = nil
self.separatorView = nil
self.btnEdit = nil
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.addView()
self.setConstraint()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextFieldCell {
func addView(){
self.contentView.addSubview(self.btnEdit)
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.textView)
self.contentView.addSubview(self.separatorView)
}
func setConstraint(){
// This part is very important to increase the textview height dyamically
let textViewHeight = self.textView.heightAnchor.constraint(equalToConstant: 27)
textViewHeight.priority = .defaultHigh
self.textView.setContentCompressionResistancePriority(.required, for: .vertical)
self.textView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
NSLayoutConstraint.activate([
self.titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 27),
self.titleLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 38),
self.textView.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 9),
self.textView.leadingAnchor.constraint(equalTo: self.titleLabel.leadingAnchor),
textViewHeight,
self.textView.trailingAnchor.constraint(equalTo: self.btnEdit.leadingAnchor, constant: -25),
self.btnEdit.centerYAnchor.constraint(equalTo: self.textView.centerYAnchor),
self.btnEdit.widthAnchor.constraint(equalToConstant: 40),
self.btnEdit.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -33),
self.separatorView.topAnchor.constraint(equalTo: self.textView.bottomAnchor, constant: 10),
self.separatorView.heightAnchor.constraint(equalToConstant: 1),
self.separatorView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
self.separatorView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 27),
self.separatorView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -15),
])
}
}
extension TextFieldCell {
#objc func actionEdit(_ sender: UIButton) {
}
}
extension TextFieldCell: UITextViewDelegate {
func notifyViewController(text:String){
}
func textViewDidEndEditing(_ textView: UITextView) {
}
}

Related

UILabel in a custom UIButton that adjusted to the button's size with AutoLayout

I want to have UILabel inside a custom UIButton with constraints to the button size, but to adjust the leading and trailing constraints constants.
The idea is to make the UILabel a bit smaller than the button width (the label takes the font from the button and uses auto shrink).
Adding the relevant code in init with coder of my custom button results with unsatisfied constraints error.
label = UILabel(frame: bounds)
addSubview(label)
translatesAutoresizingMaskIntoConstraints = false
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10.0).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
When I remove the "10.0" constant it works ok, but that idea is to give the label a different size, not the exact size of the button.
Any idea?
Thanks
Instead of additional label and constraints, try to set button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0), and use the regular title of the button.
Instead of regular UIButton, create a subclass of it, and override the intrinsicContentSize method of the button to keep the possibility of autosizing:
class MyButton : UIButton {
open override var intrinsicContentSize: CGSize {
get {
var ics = super.intrinsicContentSize
ics.width = (ics.width < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.width + self.titleEdgeInsets.left + self.titleEdgeInsets.right)) : ics.width
ics.height = (ics.height < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.height + self.titleEdgeInsets.top + self.titleEdgeInsets.bottom)) : ics.height
return ics
}
}
}
If you need two labels (native button's titleLabel + your label), the approach is the same:
class MyButton : UIButton {
var labelLeading : NSLayoutConstraint!
var labelTrailing : NSLayoutConstraint!
var labelTop : NSLayoutConstraint!
var labelBottom : NSLayoutConstraint!
let label = UILabel(frame: bounds)
public override init(frame: CGRect) {
super.init(frame: frame)
internalInit()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
internalInit()
}
private func internalInit() {
addSubview(label)
/// !!! Important to make label to not translate its autoresizing mask, not the button
label.translatesAutoresizingMaskIntoConstraints = false
labelLeading = label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10.0)
labelTrailing = label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
labelTop = label.topAnchor.constraint(equalTo: topAnchor)
labelBottom = label.bottomAnchor.constraint(equalTo: bottomAnchor)
NSLayoutConstraint.activate([labelLeading, labelTrailing, labelTop, labelBottom)
}
open override var intrinsicContentSize: CGSize {
get {
var ics = super.intrinsicContentSize
ics.width = (ics.width < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.width + self.titleEdgeInsets.left + self.titleEdgeInsets.right)) : ics.width
ics.height = (ics.height < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.height + self.titleEdgeInsets.top + self.titleEdgeInsets.bottom)) : ics.height
return ics
}
}
}
Found the solution, had to add the translatesAutoresizingMaskIntoConstraints also to the label:
label.translatesAutoresizingMaskIntoConstraints = false

Wrap label around UIbutton

I'm trying to create a view like below using storyboard in Xcode.
For this, I've added a button and a label with constraints but this is the result I get. The text doesn't start below the checkbox. One way to achieve this would be to create 2 labels and add the strings that start after this string to 2 label and place it under the first label.
Is there any better way to do this? Also, when you click on Read more the text can expand as well.
You can make the leading of the button and the label the same ( button above label ) and insert some empty characters at the beginning of the label text
You can do a way. Take the button and the label in a view
then sub divide the view into two views, left one holds the button and right one holds the label. make a gap between left and right
button's constraint will be leading , top and trailing to zero and height as your wish
label's constraint will be leading , top, trailing and bottom.
You can accomplish this by using a UITextView and setting an ExclusionPath.
The ExclusionPath (or paths) defines an area within the text view's textContainer around which the text should wrap.
If you disable scrolling, selection and editing of the UITextView it will behave just like a UILabel but will also give you the benefit of ExclusionPath
Here is a simple example - lots of hard-coded values, so you'd probably want to make it a custom class - but this should get you on your way:
class TextViewLabel: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
isScrollEnabled = false
isEditable = false
isSelectable = false
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
}
}
class ExclusionViewController: UIViewController {
let checkBox: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let theTextViewLabel: TextViewLabel = {
let v = TextViewLabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "I agree to receive information about this application and all the updates related to this..."
v.font = UIFont.systemFont(ofSize: 20.0)
return v
}()
var isChecked: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(theTextViewLabel)
theTextViewLabel.addSubview(checkBox)
let cbWidth = CGFloat(20)
NSLayoutConstraint.activate([
theTextViewLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0),
theTextViewLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0),
theTextViewLabel.widthAnchor.constraint(equalToConstant: 240.0),
checkBox.topAnchor.constraint(equalTo: theTextViewLabel.topAnchor, constant: 2.0),
checkBox.leadingAnchor.constraint(equalTo: theTextViewLabel.leadingAnchor, constant: 0.0),
checkBox.widthAnchor.constraint(equalToConstant: cbWidth),
checkBox.heightAnchor.constraint(equalToConstant: cbWidth),
])
theTextViewLabel.textContainer.exclusionPaths = [
UIBezierPath(rect: CGRect(x: 0, y: 0, width: cbWidth + 8.0, height: cbWidth))
]
updateCheckboxImage()
checkBox.addTarget(self, action: #selector(checkBoxTapped), for: .touchUpInside)
}
func updateCheckboxImage() -> Void {
if isChecked {
checkBox.setImage(UIImage(named: "SmallChecked"), for: .normal)
} else {
checkBox.setImage(UIImage(named: "SmallUnChecked"), for: .normal)
}
}
#objc func checkBoxTapped() -> Void {
isChecked = !isChecked
updateCheckboxImage()
}
}
Result:
(I used these two images for the checkBox):

textViewDidChange is only changing when a full string is typed. I want it to check every character

I have a UITextView that dynamically changes in height when text is typed beyond it's frame's bounds. However, the height will only change once the full string is typed and you press space. This leaves an awkward moment where the user can't see the word they're typing.
How can I have my textViewDidChange react for every character typed rather than when a full string is entered?
This is the initialized variable:
lazy var descriptionTextView: UITextView = {
let tv = UITextView()
tv.backgroundColor = .white
tv.font = UIFont.systemFont(ofSize: 18)
tv.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
tv.translatesAutoresizingMaskIntoConstraints = false
tv.delegate = self
tv.isScrollEnabled = false
return tv
}()
Then I add it to the subview and anchor it in my viewDidLoad:
view.addSubview(descriptionTextView)
descriptionTextView.anchor(top: privacyLabel.bottomAnchor, left:
view.leftAnchor, bottom: descriptionTextViewUnderLine.topAnchor, right: view.rightAnchor, paddingTop: 16, paddingLeft: 24, paddingBottom: 0, paddingRight: 24, width: 0, height: 40)
In an extension, I put textViewDidChange
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: view.frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
Thanks in advance for your help!
textViewDidChange(...) actually should react for every character entered (via keyboard, not programmatically). It's possible that textView.sizeThatFits(...) doesn't return what you want. A quick look at the documentation doesn't reveal an override to UIView's implementation, which just returns the same size of of the view.
NSAttributedString's boundingRect(with:options:context:) might be worth looking into to get back the desired size of the text (and thus of the view).
Also note my comment to your question. Setting scrollEnabled to false should already set the intrinsic size of the textView to the size that you need, and you shouldn't even have to set a height constraint. If your textView is getting squashed between views with constraints of equal priority, you can raise the compressionResistancePriority along the vertical axis.
A quick snippet to illustrate the example (not an answer to your question, but maybe a different approach to what you're trying to do):
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController, UITextViewDelegate {
private lazy var textView = UITextView()
override func loadView() {
let view = UIView()
view.backgroundColor = .orange
textView.frame = view.bounds
textView.backgroundColor = .white
textView.isScrollEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textView)
NSLayoutConstraint.activate(
[textView.topAnchor.constraint(equalTo: view.topAnchor),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor)]
)
textView.delegate = self
self.view = view
}
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
I have implemented this using constraints in storyboard.
The storyboard is like below:
Code that I have added in Controller is :
class ViewController: UIViewController {
#IBOutlet weak var messageTextView: UITextView!
#IBOutlet weak var messageTextViewHeightConstraint: NSLayoutConstraint!
}
extension ViewController: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
resizeTextView(textView: textView)
}
func resizeTextView(textView: UITextView) {
let sizeThatFitsTextView = messageTextView.sizeThatFits(CGSize(width: messageTextView.frame.width, height: CGFloat(MAXFLOAT)))
messageTextViewHeightConstraint.constant = sizeThatFitsTextView.height
}
}
I am changing the height of the UITextView dynamically using constraints here and it increases if you will add text beyond it's frame.
Hope this helps to achieve what you want.
You need to use UITextView frame instead of UIView.
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: textView.frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}

Swift 3: UITextView - Dynanmic height - Programmatically

I have a keyboardContainer class (Subclass of UIView / created programmatically so no storyboard) including a UITextView for the user to type messages in. It is used within a Chat log class and set as the inputAccessoryView. I want to dynamically change the height of it when the user is typing.
I searched for answers and found some. However, I didn't get most of them as they didn't work for me.
What do I have to implement to get the effect I want to have?
Thank´s for your help!
EDIT:
First of all thank you for your help!
However, I´m pretty new to coding so I could not solve the issue. I guess it has something to do with the way I created my keyboardContainer class and its constraints...
Here is the relevant code from within my keyboard container class:
let textField:UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
view.font = UIFont.systemFont(ofSize: 15)
view.backgroundColor = .white
return view
}()
overried init(frame: CGRect){
super.init(frame: frame)
addSubview(textField)
textField.leftAnchor.constraint(equalTo: leftButton, constant: 5).isActive = true
textField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
textFieldHeightAnchor = textField.heightAnchor.constraint(equalTo: heightAnchor, constant: -10)
textFieldHeightAnchor.isActive = true
textFieldRightAnchor = textField.rightAnchor.constraint(equalTo: rightAnchor, constant: -85)
textFieldRightAnchor.isActive = true
}
Inside my ChatLog I´m using this:
lazy var keyboard: KeyboardContainer = {
let key = KeyboardContainer()
key.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 45)
key.sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
return key
}()
override var inputAccessoryView: UIView?{
get{
return keyboard
}
}
What do I need to change ? I guess the constraints?
You can make your textView conform to the UITextViewDelegate and then resize it to it's contentSize.
Make your view controller conform to the delegate
class ViewController: UIViewController, **UITextViewDelegate** { ...
After that
yourTextView.delegate = self // put that in viewDidLoad()
Then you can implement the textViewDidChange method. That means, every time you enter something into the keyboard, this function is called.
func textViewDidChange(_ textView: UITextView) {
if textView == youTextView {
let currentHeight = textView.frame.size.height
textView.frame.size.height = 0 // you have to do that because if not it's not working with the proper content size
textView.frame.size = textView.contentSize // here you detext your textView's content size and make it resize.
let newHeight = textView.frame.size.height
let heightDifference = newHeight - currentHeight // get the height difference from before and after editing
yourContainerView.frame.size.height += heightDifference
}
}
Just disable the scrolling. Don't set any other constraints. This might help you with this.
In your viewDidLoad method,
YourTextView.translatesAutoresizingMaskIntoConstraints = true
YourTextView.sizeToFit()
YourTextView.isScrollEnabled = false
YourTextView.delegate = self
YourTextView.isEditable = true
Then use UITextViewDelegate and,
func textViewDidChange(_ textView: UITextView) {
MyTextView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 100)
MyTextView.translatesAutoresizingMaskIntoConstraints = true
MyTextView.sizeToFit()
MyTextView.isScrollEnabled = false
}
This was before the change,
This was after,
If you are looking for UITextView like any message app.
No need to deal with code you can manage it using constraints only.
Seems a better way to do this using constraints rather than deal with more coding.
Here is the step by step explanation of this.
Step : 1
Arrange UItextView and UIBUtton inside one UIView and give height constraint to UIView with low priority.
Step : 2
Also give height constraint to UITextView with Greater Then or Equal. as image represent it.
Step : 3
Now you just have to deal with contentSize and isScrollEnabled as below snippet.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{
if (textView.contentSize.height < 150){
textView.isScrollEnabled = false
}
else{
textView.isScrollEnabled = true
}
return true
}
Hope this help you!!

label is not growing when the text is longer

I want a view that is centered in the superview but that grows due the content in this case a label. But I don't want it to grow that it doesn't fit in the screen anymore so thats why I pin the left and right.
I've put on a test viewcontroller:
import UIKit
import PureLayout
final class ViewController: UIViewController {
let container: UIView = {
let container = UIView(forAutoLayout: ())
container.backgroundColor = UIColor.blackColor()
container.clipsToBounds = true
return container
}()
let label: UILabel = {
let label = UILabel(forAutoLayout: ())
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.textColor = UIColor.redColor()
label.text = "This is a very very very long message"
return label
}()
var rightView: UIView = {
let view = UIView(forAutoLayout: ())
view.backgroundColor = .redColor()
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.container.addSubview(self.label)
self.view.addSubview(self.container)
self.view.addSubview(self.rightView)
self.container.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 20)
self.container.autoAlignAxisToSuperviewAxis(.Vertical)
self.container.autoSetDimension(.Height, toSize: 36)
self.container.layer.cornerRadius = 18
self.container.autoPinEdge(.Right, toEdge: .Left, ofView: self.rightView, withOffset: -20, relation: .LessThanOrEqual)
self.container.autoPinEdgeToSuperviewEdge(.Left, withInset: 20, relation: .GreaterThanOrEqual)
self.container.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
self.label.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10, 20, 10, 20))
self.rightView.autoPinEdgeToSuperviewEdge(.Right, withInset: 5)
self.rightView.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 20)
self.rightView.autoSetDimension(.Width, toSize: 50)
self.rightView.autoSetDimension(.Height, toSize: 60)
}
}
The result of this is:
Why is the black view not growing until it can't due the left and right constraint? The number of lines is 1 and the ContentCompressionResistancePriority is on?
You can change the font size to fit the width of the UILabel (non-multiline):
label.numberOfLines = 1;
label.adjustsFontSizeToFitWidth = true;
label.sizeToFit();
You need dynamic changes in height means then you can do like following
Dynamic UILabel changes
label.preferredMaxLayoutWidth = 500;
you can use the above code for set preferred max width, All the best :)
What are the leading and trailing constraints on the label, you could set the leading constraint to an inequality like greater than or equal something like 5. If you're happy for the font to get smaller, you could set adjustsFontSizeToFitWidth to YES.
Try this
testLabel.text = "long text......."
testLabel.numberOfLines = 0
testLabel.sizeToFit()
Set the label.numberOfLines = 0 in your code then only it will expand based the text that you have.
Im using xcode 4. I have tested this issue
Xcode screenshot
After running in iPhone 6
Since you have a view besides the label,It wont come delete or move the view to another layer so that the label resizes automatically with code
[labelName sizeToFit];

Resources