2012-12-18 31 views
3

我有這個相對簡單的問題。 想象一下,我有一個UILabel,裏面有一些文字。然後,我想在左邊或者右邊的 文本中也顯示一個圖像(添加)。在UILabel左側添加圖片

事情是這樣的:

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

有沒有辦法做到這一點,利用,說UILabel方法?我沒有找到這樣的。

+0

這就是所謂的UIImageView。 – jimpic

+0

我知道,但在我的功能(請看看我鏈接的圖像),我基本上想要標籤內嵌入的uiimageview(或只是圖像)。我清楚了嗎?謝謝。我希望他們都在一個單一的控制。舉例來說,我期望的UILabel有這樣的方法:myLabel.addImageToTheLeft()...等 – user1903992

+0

可能重複[如何嵌入的UILabel小圖標](http://stackoverflow.com/questions/19318421/how - 嵌入 - 小圖標在uilabel) – bummi

回答

1

創建一個包含一個UIImageView和的UILabel子視圖自定義的UIView。您必須在內部執行幾何邏輯來調整標籤的大小以適合左側或右側的圖像,但不應太多。

+1

嗨,謝謝。所以沒有內置的方法來做到這一點?其實現在我正在像你說的那樣行事。我有一個視圖和兩個子視圖:一個UILabel和一個UIimageView(兩者都使用Interface Builder進行定位)。我認爲這應該以這種方式工作?謝謝。 – user1903992

1

創建你的形象一個UIImageView和像

[imageview addSubView:label]; 

設置標籤的框架中添加的UILabel之上據此您需要的位置。

7

萬一別人在未來看這件事。我會繼承UIlabel類並添加一個圖像屬性。

然後你就可以覆蓋文本和圖像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)]; 
} 
+0

我剛剛用這個方法,想添加一些注意事項: 爲了在IB工作的內在內容大小正確此標籤的子類,你也應該重寫intrinsicContentSize法覈算額外的寬度。 此外,使用帶附件的NSAttributedString可能是一種更理想的方法。 – BreadicalMD

0

我只是執行我的直播項目類似的事情,希望它會有幫助。

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