iOSNoob
iOSNoob

Reputation: 1420

How to change UILabel width based on text length in iOS?

I want to display an image next to a 'UILabel', however 'UILabel' has variable text length, so I don't know where to place the image.

Image should move according to the size of the label.

How can I accomplish this?

Upvotes: 4

Views: 13447

Answers (4)

Suragch
Suragch

Reputation: 512586

I had the same question and I wanted to do this in the storyboard with autolayout and not in code. So I made the following app to test out the concept.

enter image description here

I added Auto Layout constraints for the "Variable Text Label" and the image. I pinned the label to the left edge of the container (but I didn't set any constraints for the width). Then I pinned the image to the right edge of the label. (I also added constraints to "Vertical Center in Container" for both the label and the image.)

When I changed the label text programmatically, the image automatically changed its position and stayed next to the label.

Here is the simple code I used. (Sorry, its in Swift, not objective-C.)

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var myLabel: UILabel!

    @IBAction func button(sender: AnyObject) {
        myLabel.text = textField.text
    }
}

For other people who view this question and don't know how to even add constraints (like me not long ago), here is another one of my answers.

Upvotes: 1

theiOSDude
theiOSDude

Reputation: 1470

Although Keshav answer will work, it's deprecated

try:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};

CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];

Then use the Size of rect to determine your positioning and label size.

CGRect currentLabelFrame = self.label.frame;

currentLabelFrame.size.width = rect.size.width;

self.label.frame = currentLabelFrame;

Upvotes: 5

Keshav
Keshav

Reputation: 3273

you can use the below code:

label.numberOfLines = 0;
CGRect frame = label.frame;
labelSize = [@"message" sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
frame.size = labelSize;
label.frame = frame;

Upvotes: 0

Anil
Anil

Reputation: 2438

Using auto layout, you can do the following:

  1. Set the numberOfLines property to 0
  2. Set width constraint of the UILabel (click on the label, bottom right there's an icon with a box in between two lines (Pin))
  3. Select the constraint and edit the value in the Size Inspector (top right, second last icon) of the width constraint and change the constant '=' to '>='

Upvotes: 3

Related Questions