Reputation: 1420
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
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.
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
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
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
Reputation: 2438
Using auto layout, you can do the following:
Upvotes: 3