この比較的単純な質問があると思います。UILabel
いくつかのテキストが含まれていると想像してください。次に、テキストの左側または右側にも画像を表示(追加)したいと思います。
このようなもの:
http://www.zazzle.com/blue_arrow_button_left_business_card_templates-240863912615266256
たとえばメソッドを使用して、それを行う方法はありUILabel
ますか?私はそのようなものを見つけられませんでした。
この比較的単純な質問があると思います。UILabel
いくつかのテキストが含まれていると想像してください。次に、テキストの左側または右側にも画像を表示(追加)したいと思います。
このようなもの:
http://www.zazzle.com/blue_arrow_button_left_business_card_templates-240863912615266256
たとえばメソッドを使用して、それを行う方法はありUILabel
ますか?私はそのようなものを見つけられませんでした。
誰か他の人が将来これを調べた場合に備えて。UIlabelクラスをサブクラス化し、画像プロパティを追加します。
次に、textおよびimageプロパティのセッターをオーバーライドできます。
- (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)];
}
UIImageViewおよびUILabelサブビューを含むカスタムUIViewを作成します。左または右の画像に合うようにラベルのサイズを設定するには、ジオメトリロジックを実行する必要がありますが、多すぎないようにする必要があります。
画像を使用してUIImageViewを作成し、その上にUILabelを追加します。
[imageview addSubView:label];
ラベルのフレームを必要な位置に合わせて設定します。
ライブプロジェクトで同様のことを実装しました。お役に立てば幸いです。
-(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;
}