How to embed small icon in UILabel
You can do this with iOS 7's text attachments, which are part of TextKit. Some sample code:
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;
Here is the way to embed icon in UILabel.
Also to Align the Icon use attachment.bounds
Swift 5.1
// Create Attachmentlet imageAttachment = NSTextAttachment()imageAttachment.image = UIImage(named:"iPhoneIcon")// Set bound to repositionlet imageOffsetY: CGFloat = -5.0imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: imageAttachment.image!.size.width, height: imageAttachment.image!.size.height)// Create string with attachmentlet attachmentString = NSAttributedString(attachment: imageAttachment)// Initialize mutable stringlet completeText = NSMutableAttributedString(string: "")// Add image to mutable stringcompleteText.append(attachmentString)// Add your text to mutable stringlet textAfterIcon = NSAttributedString(string: "Using attachment.bounds!")completeText.append(textAfterIcon)self.mobileLabel.textAlignment = .centerself.mobileLabel.attributedText = completeText
Objective-C Version
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;
Swift 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