问题
I want to have an UILabel with a max width of 100 and after that an UIImage, how can I do that in interface builder? I want that if the text is shorter the label is less than 100 but the UIImage is right behind the label.
回答1:
you can do it with code like this:
first init the label and the imageView
_label = [[UILabel alloc] initWithFrame:CGRectZero];
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, label.frame.origin.y, 30, 30)];
then when the label has text , you can calc the width of the label`s frame
CGSize size = [_label.text sizeWithFont:[UIFont boldSystemFontOfSize:15]];
CGFloat width = size.width > 100 ? 100 : size.width;
CGFloat height = size.height;
_label.frame = CGRectMake(0, 0, width, height);
回答2:
You can use NSTextAttachment class available from iOS 7.No need to play with the frame.
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"image.png"];
NSAttributedString *attachmentAttrString = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithString:@"hello"];
[str appendAttributedString:attachmentAttrString];
myLabel.attributedText = str;
回答3:
I'd like to add my swift solution:
let label = UILabel()
let attributedString = NSMutableAttributedString(string: "Hello".uppercaseString)
let attachment = NSTextAttachment()
attachment.image = UIImage(named:"hello")
attributedString.appendAttributedString(NSAttributedString(attachment:attachment))
// use the following method to insert the image at any index
// attributedString.insertAttributedString(NSAttributedString(attachment:attachment), atIndex: 0)
label.attributedText = attributedString
来源:https://stackoverflow.com/questions/12968643/place-an-uiimage-after-an-uilabel