Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add image to the left of a UILabel

I have this relatively simple question, I think. Imagine I have a UILabel with some text in it. Then, I want on the left, or right side of the text also an image to be displayed (added).

Something like this:

http://www.zazzle.com/blue_arrow_button_left_business_card_templates-240863912615266256

Is there a way to do it, using, say UILabel methods? I didn't find such.

like image 505
user1903992 Avatar asked Dec 26 '22 12:12

user1903992


2 Answers

I just implemented similar thing in my Live Project, hope it will be helpful.

-(void)setImageIcon:(UIImage*)image WithText:(NSString*)strText{

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    float offsetY = -4.5; //This can be dynamic with respect to size of image and UILabel
    attachment.bounds = CGRectIntegral( CGRectMake(0, offsetY, attachment.image.size.width, attachment.image.size.height));

    NSMutableAttributedString *attachmentString = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:strText];

    [attachmentString appendAttributedString:myString];

    _lblMail.attributedText = attachmentString;
}
like image 32
Mrug Avatar answered Jan 08 '23 16:01

Mrug


Just in case someone else look this up in the future. I would subclass the UIlabel class and add an image property.

Then you can override the setter of the text and image property.

- (void)setImage:(UIImage *)image {
    _image = image;

    [self repositionTextAndImage];
}

- (void)setText:(NSString *)text {
    [super setText:text];

    [self repositionTextAndImage];
}

In repositionTextAndImage, you can do your positioning calculation. The code I pasted, just insert an image on the left.

- (void)repositionTextAndImage {
    if (!self.imageView) {
        self.imageView = [[UIImageView alloc] init];
        [self addSubview:self.imageView];
    }

    self.imageView.image = self.image;
    CGFloat y = (self.frame.size.height - self.image.size.height) / 2;
    self.imageView.frame = CGRectMake(0, y, self.image.size.width, self.image.size.height);
}

Lastly, override drawTextInRect: and make sure you leave space on the left of your label so that it does not overlap with the image.

- (void)drawTextInRect:(CGRect)rect {
    // Leave some space to draw the image.
    UIEdgeInsets insets = {0, self.image.size.width + kImageTextSpacer, 0, 0};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
like image 57
user3391404 Avatar answered Jan 08 '23 18:01

user3391404