问题
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?
回答1:
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;
回答2:
Using auto layout, you can do the following:
- Set the numberOfLines property to 0
- Set width constraint of the UILabel (click on the label, bottom right there's an icon with a box in between two lines (Pin))
- 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 '>='
回答3:
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.
回答4:
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;
来源:https://stackoverflow.com/questions/26358146/how-to-change-uilabel-width-based-on-text-length-in-ios