将图像添加到UILabel的左侧

use*_*992 3 cocoa-touch ios

我想,我有这个相对简单的问题.想象一下,我有UILabel一些文字.然后,我想在文本的左侧或右侧还显示(添加)图像.

像这样的东西:

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

有没有办法做到这一点,使用UILabel方法呢?我没有找到这样的.

小智 7

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

然后,您可以覆盖text和image属性的setter.

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

    [self repositionTextAndImage];
}

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

    [self repositionTextAndImage];
}
Run Code Online (Sandbox Code Playgroud)

在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);
}
Run Code Online (Sandbox Code Playgroud)

最后,覆盖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)];
}
Run Code Online (Sandbox Code Playgroud)