Edited at

UILabelに画像を表示するためのカテゴリを書いてみた

More than 3 years have passed since last update.


やりたかったこと

UILabelと画像を一緒に扱いたい時が多々あるので、そのためのカテゴリーを書いてみた。


内容

デフォルトではstringとimageを渡すと、先頭に画像がくるようにしてます。

画像の位置と文字の何番目に画像を入れるか、も指定できるように。


実装

NSMutableAttributedString+UIImage.h


@interface NSMutableAttributedString (UIImage)

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image;

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image atIndex:(NSUInteger)index;

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image point:(CGPoint)point;

- (instancetype)initWithString:(NSString *)string
image:(UIImage *)image
point:(CGPoint)point
atIndex:(NSUInteger)index;
@end

NSMutableAttributedString+UIImage.m


#import "NSMutableAttributedString+UIImage.h"

@implementation NSMutableAttributedString (UIImage)

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image {
return [self initWithString:string image:image point:CGPointZero atIndex:0];
}

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image atIndex:(NSUInteger)index {
return [self initWithString:string image:image point:CGPointZero atIndex:index];
}

- (instancetype)initWithString:(NSString *)string image:(UIImage *)image point:(CGPoint)point {
return [self initWithString:string image:image point:point atIndex:0];
}

- (instancetype)initWithString:(NSString *)string
image:(UIImage *)image
point:(CGPoint)point
atIndex:(NSUInteger)index {
if (!string) {
return nil;
}
self = [self initWithString:string];
if (self) {
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;
textAttachment.bounds = CGRectMake(point.x, point.y, image.size.width, image.size.height);
NSAttributedString *attributedString =
[NSAttributedString attributedStringWithAttachment:textAttachment];
[self insertAttributedString:attributedString atIndex:index];
}
return self;
}

@end


使用イメージ


- (void)viewDidLoad {
self.contentLabel.attributedText =
[[NSMutableAttributedString alloc] initWithString:@"あいうえお"
image:[UIImage imageNamed:@"test"]
point:CGPointMake(0, -2)];
self.contentLabel.attributedText =
[[NSMutableAttributedString alloc] initWithString:@"あいうえお"
image:[UIImage imageNamed:@"test"]
point:CGPointMake(0,-10)
atIndex:2];

}


参考

UILabelに画像を表示する