4

この比較的単純な質問があると思います。UILabelいくつかのテキストが含まれていると想像してください。次に、テキストの左側または右側にも画像を表示(追加)したいと思います。

このようなもの:

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

たとえばメソッドを使用して、それを行う方法はありUILabelますか?私はそのようなものを見つけられませんでした。

4

4 に答える 4

7

誰か他の人が将来これを調べた場合に備えて。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)];
}
于 2014-03-28T23:49:31.970 に答える
1

UIImageViewおよびUILabelサブビューを含むカスタムUIViewを作成します。左または右の画像に合うようにラベルのサイズを設定するには、ジオメトリロジックを実行する必要がありますが、多すぎないようにする必要があります。

于 2012-12-18T11:50:42.187 に答える
1

画像を使用してUIImageViewを作成し、その上にUILabelを追加します。

[imageview addSubView:label];

ラベルのフレームを必要な位置に合わせて設定します。

于 2012-12-18T11:50:48.467 に答える
1

ライブプロジェクトで同様のことを実装しました。お役に立てば幸いです。

-(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;
}
于 2016-02-04T07:24:44.233 に答える