将图像添加到UILabel的左侧

时间:2012-12-18 11:28:03

标签: ios cocoa-touch

我认为这是一个相对简单的问题。 想象一下,我有一个UILabel,里面有一些文字。然后,我想要在左边或右边 文本也是要显示(添加)的图像。

这样的事情:

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

有没有办法,使用UILabel方法?我没有找到这样的。

5 个答案:

答案 0 :(得分:7)

以防其他人在将来查看此内容。我会继承UIlabel类并添加一个图像属性。

然后你可以覆盖text和image属性的setter。

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

    [self repositionTextAndImage];
}

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

    [self repositionTextAndImage];
}

在repositionTextAndImage中,您可以进行定位计算。我粘贴的代码,只需在左侧插入图像。

- (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);
}

最后,覆盖drawTextInRect:并确保在标签的左侧留出空格,使其不与图像重叠。

- (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)];
}

答案 1 :(得分:1)

创建一个包含UIImageView和UILabel子视图的自定义UIView。您必须在其中执行一些几何逻辑来调整标签的大小以适合左侧或右侧的图像,但它不应该太多。

答案 2 :(得分:1)

使用您的图片创建UIImageView,并将UILabel添加到顶部,如

[imageview addSubView:label];

根据您所需的位置设置标签的框架。

答案 3 :(得分:1)

我在这里发布了类似问题的答案:https://stackoverflow.com/a/31112219/553939它是用swift编写的,但代码很容易转换为Obj-C

答案 4 :(得分:1)

我刚刚在我的Live Project中实现了类似的功能,希望它会有所帮助。

-(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;
}
相关问题