UILabel'e küçük simge yerleştirme


153

UILabelİOS7'de küçük simgeleri (bir tür özel madde işareti ) gömmem gerekiyor. Bunu arayüz tasarımcısında nasıl yapabilirim? Veya en azından kodda mı?

Android'de etiketler için leftDrawableve var rightDrawable, ancak iOS'ta nasıl yapılır? Android'de örnek:

android örneği


Android ile tanışmıyorum referans için bazı görüntü gönderebilir misiniz?
— user1673099

2
küçük bir görsel görüntüleme oluşturun ve etiketin nesnesine alt görünüm olarak ekleyin
— Saurabh Passolia

Yanıtlar:


292

Bunu, iOS 7'nin TextKit'in bir parçası olan metin ekleriyle yapabilirsiniz. Bazı örnek kodlar:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];

myLabel.attributedText = myString;

İOS6'ya ne dersiniz? Hiç önerin var mı?? Teşekkürler
— Steven Jiang

1
@StevenJiang: UIImageViewEtiketinize bir tane eklemeniz gerekecek
— Scott Berrevoets

1
Ne yazık ki bu simgeyi metnin arkasına yerleştirir. Bunu bir metin bulamadığımız için herhangi bir şansımız var mı ?!
— Ters

4
@reVerse Görüntüyü (ek dizesi) metin dizenize eklemek yerine, bunu tersine deneyebilirsiniz, böylece metin dizesini ek dizesine ekleyebilirsiniz.
— Scott Berrevoets

11
Bunu zaten dün denemiştim. Bir şey kaçırılmış gibi görünüyor çünkü şimdi çalışıyor. Teşekkürler. Aynı şeyi yapmaya çalışan herkes için (biraz farklı olduğu için): NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString]; NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:text]; [myString appendAttributedString:myText];
— 14'te

153

UILabel'e simge yerleştirmenin yolu.

Ayrıca Simgeyi Hizalamak için attachment.bounds kullanın


Swift 5.1

// Create Attachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"iPhoneIcon")
// Set bound to reposition
let imageOffsetY: CGFloat = -5.0
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: imageAttachment.image!.size.width, height: imageAttachment.image!.size.height)
// Create string with attachment
let attachmentString = NSAttributedString(attachment: imageAttachment)
// Initialize mutable string
let completeText = NSMutableAttributedString(string: "")
// Add image to mutable string
completeText.append(attachmentString)
// Add your text to mutable string
let textAfterIcon = NSAttributedString(string: "Using attachment.bounds!")
completeText.append(textAfterIcon)
self.mobileLabel.textAlignment = .center
self.mobileLabel.attributedText = completeText

Objective-C Versiyonu

NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
imageAttachment.image = [UIImage imageNamed:@"iPhoneIcon"];
CGFloat imageOffsetY = -5.0;
imageAttachment.bounds = CGRectMake(0, imageOffsetY, imageAttachment.image.size.width, imageAttachment.image.size.height);
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:imageAttachment];
NSMutableAttributedString *completeText = [[NSMutableAttributedString alloc] initWithString:@""];
[completeText appendAttributedString:attachmentString];
NSAttributedString *textAfterIcon = [[NSAttributedString alloc] initWithString:@"Using attachment.bounds!"];
[completeText appendAttributedString:textAfterIcon];
self.mobileLabel.textAlignment = NSTextAlignmentRight;
self.mobileLabel.attributedText = completeText;

resim açıklamasını buraya girin

resim açıklamasını buraya girin


22
Eklenti için oy verin.
— Peter Zhao

3
Attachment.bounds kullanımı için harika çağrı. Tam da aradığım şey buydu.
— Geoherna

2
Aslında, -5.0 sabit değeri kullanmak yerine imageOffsetY hesaplanabilir. imageOffsetY: CGFloat = - (imageAttachment.image! .size.height - self.mobileLabel.font.pointSize) / 2.0;
— JonSlowCN

Not: Derleme süresini yavaşlatır
— Jack

Film şeridinde yapabilir miyim?
— Augusto

53

Hızlı 4.2:

let attachment = NSTextAttachment()        
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.append(attachmentString)
label.attributedText = myString

23

Referans resminiz bir düğmeye benziyor. Deneyin (Arayüz Oluşturucu'da da yapılabilir):

resim açıklamasını buraya girin

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(50, 50, 100, 44)];
[button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
[button setTitle:@"Abc" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor yellowColor]];
[view addSubview:button];

İyi açıkladı, bir ref sağlamak için zaman ayırdığınız gerçeğini seviyorum. Bana çok yardımcı oldu! Teşekkürler
— Shinnyx

Bu, kupa ikonumu bir düğmeye yerleştirmeye yardımcı oldu. Çok teşekkürler!
— Harish

23

Swift 3 sürümü

let attachment = NSTextAttachment()
attachment.image = UIImage(named: "plus")
attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
let attachmentStr = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "")
myString.append(attachmentStr)
let myString1 = NSMutableAttributedString(string: "My label text")
myString.append(myString1)
lbl.attributedText = myString

UILabel Uzantısı

extension UILabel {

    func set(text:String, leftIcon: UIImage? = nil, rightIcon: UIImage? = nil) {

        let leftAttachment = NSTextAttachment()
        leftAttachment.image = leftIcon
        leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: 20, height: 20)
        if let leftIcon = leftIcon {
            leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: leftIcon.size.width, height: leftIcon.size.height)
        }
        let leftAttachmentStr = NSAttributedString(attachment: leftAttachment)

        let myString = NSMutableAttributedString(string: "")

        let rightAttachment = NSTextAttachment()
        rightAttachment.image = rightIcon
        rightAttachment.bounds = CGRect(x: 0, y: -5, width: 20, height: 20)
        let rightAttachmentStr = NSAttributedString(attachment: rightAttachment)


        if semanticContentAttribute == .forceRightToLeft {
            if rightIcon != nil {
                myString.append(rightAttachmentStr)
                myString.append(NSAttributedString(string: " "))
            }
            myString.append(NSAttributedString(string: text))
            if leftIcon != nil {
                myString.append(NSAttributedString(string: " "))
                myString.append(leftAttachmentStr)
            }
        } else {
            if leftIcon != nil {
                myString.append(leftAttachmentStr)
                myString.append(NSAttributedString(string: " "))
            }
            myString.append(NSAttributedString(string: text))
            if rightIcon != nil {
                myString.append(NSAttributedString(string: " "))
                myString.append(rightAttachmentStr)
            }
        }
        attributedText = myString
    }
}

17

Bu özelliğin hızlı bir şekilde uygulanmasını burada yaptım: https://github.com/anatoliyv/SMIconLabel

Kod mümkün olduğunca basit:

var labelLeft = SMIconLabel(frame: CGRectMake(10, 10, view.frame.size.width - 20, 20))
labelLeft.text = "Icon on the left, text on the left"

// Here is the magic
labelLeft.icon = UIImage(named: "Bell") // Set icon image
labelLeft.iconPadding = 5               // Set padding between icon and label
labelLeft.numberOfLines = 0             // Required
labelLeft.iconPosition = SMIconLabelPosition.Left // Icon position
view.addSubview(labelLeft)

İşte böyle görünüyor:

SMIconLabel resmi


13

UIlabelYukarıdaki cevaplara referansla Etikete Resim eklemek için Swift 4 Uzantısı

extension UILabel {
  func set(image: UIImage, with text: String) {
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    let attachmentStr = NSAttributedString(attachment: attachment)

    let mutableAttributedString = NSMutableAttributedString()
    mutableAttributedString.append(attachmentStr)

    let textString = NSAttributedString(string: text, attributes: [.font: self.font])
    mutableAttributedString.append(textString)

    self.attributedText = mutableAttributedString
  }
}

NSAttributedString(string: " " + text, attributes: [.font: self.font])
— Farzad

@grizzly, simge ve metin arasında boşluk oluşturmak için mi?
— Ajan Smith

Evet. ve metin arasındaki boşluk için başka bir yol nedir?
— Farzad

4

Swift 2.0 sürümü:

//Get image and set it's size
let image = UIImage(named: "imageNameWithHeart")
let newSize = CGSize(width: 10, height: 10)

//Resize image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let imageResized = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

//Create attachment text with image
var attachment = NSTextAttachment()
attachment.image = imageResized
var attachmentString = NSAttributedString(attachment: attachment)
var myString = NSMutableAttributedString(string: "I love swift ")
myString.appendAttributedString(attachmentString)
myLabel.attributedText = myString

3

UIViewIB'de ekrana a sürüklemeyi deneyin . Buradan a UIImageViewve UILabeloluşturduğunuz görünüme sürükleyebilirsiniz . İmajını ayarlayın UIImageView(eğer gezinti bölmesinde içine sürükleyerek projenize eklemek gerekir) özel mermi görüntü olarak özellikler denetçisindeki ve etiket bir metin yazabilirsiniz.


2

bu şekilde dene ...

  self.lbl.text=@"Drawble Left";
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    img.image=[UIImage imageNamed:@"Star.png"];
    [self.lbl addSubview:img];

Bu size yardımcı oldu mu?
— user1673099

bu yaklaşım görüntü için metin ofsetini özlüyor (metin görüntünün arkasında yer alıyor)
— brigadir

2

Swift 5 Kolay Yolu Sadece CopyPaste ve istediğinizi değiştirin

let fullString = NSMutableAttributedString(string:"To start messaging contacts who have Talklo, tap ")

 // create our NSTextAttachment
let image1Attachment = NSTextAttachment() 
image1Attachment.image = UIImage(named: "chatEmoji")
image1Attachment.bounds = CGRect(x: 0, y: -8, width: 25, height: 25)

// wrap the attachment in its own attributed string so we can append it
let image1String = NSAttributedString(attachment: image1Attachment)

 // add the NSTextAttachment wrapper to our full string, then add some more text.

 fullString.append(image1String)
 fullString.append(NSAttributedString(string:" at the right bottom of your screen"))

 // draw the result in a label
 self.lblsearching.attributedText = fullString

resim açıklamasını buraya girin



1

Swift 2.0'da,

Soruna çözümüm, bu soruya verilen birkaç cevabın birleşimidir. @ Phil'in cevabında karşılaştığım sorun, simgenin konumunu değiştiremedim ve her zaman köşede göründü. Ve @anatoliy_v'den gelen bir cevap, dizeye eklemek istediğim simge boyutunu yeniden boyutlandıramadım.

Benim için çalışmasını sağlamak için, önce bir pod 'SMIconLabel've daha sonra bu işlevi yarattım:

func drawTextWithIcon(labelName: SMIconLabel, imageName: String, labelText: String!,  width: Int, height: Int) {

        let newSize = CGSize(width: width, height: height)
        let image = UIImage(named: imageName)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
        let imageResized = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        labelName.text = " \(labelText)"
        labelName.icon = imageResized
        labelName.iconPosition = .Left
    }

Bu çözüm yalnızca görüntüyü yerleştirmenize yardımcı olmakla kalmayacak, aynı zamanda simge boyutu ve diğer niteliklerde gerekli değişiklikleri yapmanıza da izin verecektir.

Teşekkür ederim.


1

Swift 3 UILabel eklentisi

İpucu: Görüntü ve metin arasında biraz boşluğa ihtiyacınız varsa, labelText'ten önce bir veya iki boşluk kullanın.

extension UILabel {
    func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: imageName)
        attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
        let attachmentStr = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: "")
        string.append(attachmentStr)
        let string2 = NSMutableAttributedString(string: labelText)
        string.append(string2)
        self.attributedText = string
    }
}

1
Bunu kullandım ve mükemmel çalıştı. Yukarıdaki diğerleri aslında görüntüyü dizenin sonuna çevirdi.
— mondousage

1
 func atributedLabel(str: String, img: UIImage)->NSMutableAttributedString
{   let iconsSize = CGRect(x: 0, y: -2, width: 16, height: 16)
    let attributedString = NSMutableAttributedString()
    let attachment = NSTextAttachment()
    attachment.image = img
    attachment.bounds = iconsSize
    attributedString.append(NSAttributedString(attachment: attachment))
    attributedString.append(NSAttributedString(string: str))

    return attributedString
} 

Etikete görüntü veya küçük simgeler eklemek için bu işlevi kullanabilirsiniz


Bunu viewdidload () ile çağırın
— Ayush Dixit

let emojisCollection = [UIImage (adlı: "ic_place"), UIImage (adlı: "ic_group"), UIImage (adlı: "ic_analytics")] lbl1.attributedText = atributedLabel (str: "Howath, Dublin", img: emojisCollection [0 ]!) lbl2.attributedText = atributedLabel (str: "Zorluk: 18+", img: emojisCollection [2]!) lbl3.attributedText = atributedLabel (str: "Maksimum grup boyutu: 10", img: emojisCollection [1]!)
— Ayush Dixit

yukarıdaki yorumları eklemek için orijinal yanıtınızı düzenleyebilirsiniz.
— Moondra

0

a kullandığınız özel bir nesne yapmanız gerekir UIViewve içine a UIImageViewve aUILabel

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.