Как вставить маленькую иконку в UILabel
Мне нужно встроить маленькие иконки (вроде пользовательских маркеров) в мой UILabel
в iOS7.
Как я могу сделать это в дизайнере интерфейса? Или хотя бы в коде?
В Android есть leftDrawable
и rightDrawable
для меток, но как это сделать в iOS?
Образец в Android:
![android sample]()
Ответы
Ответ 1
Вы можете сделать это с помощью iOS 7 текстовых вложений, которые являются частью TextKit. Пример кода:
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;
Ответ 2
Вот способ вставить значок в UILabel.
Также для выравнивания значка используйте attachment.bounds
Swift 4.2
//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 = NSMutableAttributedString(string: "Using attachment.bounds!")
completeText.append(textAfterIcon)
self.mobileLabel.textAlignment = .center;
self.mobileLabel.attributedText = completeText;
Версия Objective-C
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];
NSMutableAttributedString *textAfterIcon= [[NSMutableAttributedString alloc] initWithString:@"Using attachment.bounds!"];
[completeText appendAttributedString:textAfterIcon];
self.mobileLabel.textAlignment=NSTextAlignmentRight;
self.mobileLabel.attributedText=completeText;
![enter image description here]()
![enter image description here]()
Ответ 3
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
Ответ 4
Ваше ссылочное изображение выглядит как кнопка. Попробуйте (также можно сделать в Interface Builder):
![enter image description here]()
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];
Ответ 5
Версия Swift 3
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 Extension
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
}
}
Ответ 6
Я сделал реализацию этой функции в swift здесь: https://github.com/anatoliyv/SMIconLabel
Код настолько прост, насколько это возможно:
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)
Вот как это выглядит:
![SMIconLabel image]()
Ответ 7
Swift 4 UIlabel
Расширение для добавления изображения в ярлык со ссылкой на приведенные выше ответы
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
}
}
Ответ 8
версия Swift 2.0:
//Get image and set it 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
Ответ 9
Попробуйте перетащить UIView
на экран в IB. Оттуда вы можете перетащить UIImageView
и UILabel
в только что созданный вид. Установите изображение UIImageView
в инспекторе свойств в качестве настраиваемого изображения маркера (которое вы должны будете добавить в свой проект, перетаскивая его на панель навигации), и вы можете написать текст в метке.
Ответ 10
попробуйте этот путь...
[email protected]"Drawble Left";
UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
img.image=[UIImage imageNamed:@"Star.png"];
[self.lbl addSubview:img];
Ответ 11
С помощью leftView, а затем установите для свойства enabled
значение NO
Или используйте UIButton и setImage:forControlState
Ответ 12
В Swift 2.0,
Мое решение проблемы - это комбинация нескольких ответов на этот вопрос. Проблема, с которой я столкнулся в @Phil, заключалась в том, что я не мог изменить положение значка, и он всегда появлялся прямо в углу. И один ответ от @anatoliy_v, я не мог изменить размер значка, который я хочу добавить в строку.
Чтобы он работал у меня, я сначала сделал pod 'SMIconLabel'
, а затем создал эту функцию:
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
}
Это решение не только поможет вам разместить изображение, но также позволит внести необходимые изменения в размер значка и другие атрибуты.
Спасибо.
Ответ 13
Swift 3 Расширение UILabel
Совет. Если вам нужно некоторое пространство между изображением и текстом, просто используйте пробел или два перед labelText.
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
}
}
Ответ 14
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
}
Вы можете использовать эту функцию для добавления изображений или небольших значков на ярлык
Ответ 15
вам нужно создать пользовательский объект, в котором вы использовали UIView
, и внутри вы помещаете UIImageView
и UILabel