如何将图片置于UILabel文本开头?

3

你好,我想在我的应用中为一些 UILabel 添加圆点图片。

我有添加图片的代码。但是我不知道如何将图片放在 UILabel 的开头而不是结尾。

对此有什么建议吗?下面是我用于此的代码:我应该添加什么来将图像放在 UILabel 开头?我认为 imageBehindText :false 会解决这个问题,但它没有。

extension UILabel {
/**
 This function adding image with text on label.

 - parameter text: The text to add
 - parameter image: The image to add
 - parameter imageBehindText: A boolean value that indicate if the imaga is behind text or not
 - parameter keepPreviousText: A boolean value that indicate if the function keep the actual text or not
 */
func addTextWithImage(text: String, image: UIImage, imageBehindText: Bool, keepPreviousText: Bool) {
    let lAttachment = NSTextAttachment()
    lAttachment.image = image

    // 1pt = 1.32px
    let lFontSize = round(self.font.pointSize * 1.20)   // rounded dot should be smaller than font
    let lRatio = image.size.width / image.size.height

    lAttachment.bounds = CGRect(x: 0, y: ((self.font.capHeight - lFontSize) / 2).rounded(), width: lRatio * lFontSize, height: lFontSize)

    let lAttachmentString = NSAttributedString(attachment: lAttachment)

    if imageBehindText {
        let lStrLabelText: NSMutableAttributedString

        if keepPreviousText, let lCurrentAttributedString = self.attributedText {
            lStrLabelText = NSMutableAttributedString(attributedString: lCurrentAttributedString)
            lStrLabelText.append(NSMutableAttributedString(string: text))
        } else {
            lStrLabelText = NSMutableAttributedString(string: text)
        }

        lStrLabelText.append(lAttachmentString)
        self.attributedText = lStrLabelText
    } else {
        let lStrLabelText: NSMutableAttributedString

        if keepPreviousText, let lCurrentAttributedString = self.attributedText {
            lStrLabelText = NSMutableAttributedString(attributedString: lCurrentAttributedString)
            lStrLabelText.append(NSMutableAttributedString(attributedString: lAttachmentString))
            lStrLabelText.append(NSMutableAttributedString(string: text))
        } else {
            lStrLabelText = NSMutableAttributedString(attributedString: lAttachmentString)
            lStrLabelText.append(NSMutableAttributedString(string: text))
        }

        self.attributedText = lStrLabelText
    }
}

1
为什么不直接使用水平堆栈视图并结束呢? - Adrian
我该怎么做?你的意思是我应该使用另一个标签来指定图片吗? - iOS_Android_Flutter_PRO
这是一个关于堆栈视图的快速教程。我喜欢它们。它们可以为您处理很多“簿记”工作,而且易于进行动画等操作。https://www.raywenderlich.com/2198310-uistackview-tutorial-for-ios-introducing-stack-views - Adrian
2个回答

2

我搞定了。问题在于我在storyboard(.xib)中设置了文本。因此,即使布尔值为false,此扩展也不会将图像更改为前景。

只需从函数调用中设置文本,'false'值就会触发将图像设置在uilabel的开头。

示例1(我的错误操作):

Original Answer翻译成"最初的回答"

// This is what I tried first!
    label.addTextWithImage(text: "",
                                       image: UIImage(named: embededIcon)!,
                                       imageBehindText: false, // note! This is false.
                                       keepPreviousText: true) // this was the problem!

例子2(使它工作的方法!):

最初的回答:

label.addTextWithImage(text: "putYourLabelTextHere!",  // You have to put text here, even if it's already in storyboard.
                                   image: UIImage(named: embededIcon)!,
                                   imageBehindText: false,
                                   keepPreviousText: false) // false, so the image will be set before text!

很好,你搞定了。但我鼓励你不要使用强制解包(!)。更好的处理可选项的方法是使用if let emdeddedIcon = whateverYourImageIs { do stuff }guard let embeddedIcon = whateverYourImageIs else { return }。或者,你可以只提供一个空白图片,这样第二个参数就变成了 image: UIImage(named: embeddedIcon) ?? UIImage(), - Adrian
哇,我真的错过了那个。非常感谢您的警告!我会采用您提供的替代方案,?? UIImage()。 - iOS_Android_Flutter_PRO
我不知道你的视图是什么样子的,但如果你保证有文本而图像是可选的,if let 可能是最好的选择,你可以这样做 else {设置文本并隐藏图像}。无论如何,你知道他们对意见的看法。这更像是一个六与半打问题。 - Adrian
我不确定你的意思。如果你是指embeddedIcon始终具有指向资产的text-ref,那么这是正确的。使用guard let或let的问题在于embIcon不是一个let,例如将更改图标。如果我使用let关键字,恐怕会出现错误的图标,因为该变量始终相同。 - iOS_Android_Flutter_PRO

0
lazy var attachment: NSTextAttachment = {
    let attachment = NSTextAttachment()
    attachment.image = UIImage(named: "")
    return attachment
}()

它将适用于远程和本地图像

if let imageUrl = imageUrl, imageUrl.count > 0, let url = URL(string: imageUrl) {
let imageAttachmentString = NSAttributedString(attachment: attachment)
attachment.bounds = CGRect(x: 0, y: (titleLabel.font.capHeight - 16) / 2, width: 16, height: 16)
BaseAPI().downloadImage(with: url, placeHolder: "") { [weak self]  image, error, success, url in
    if let image = image, let self = self {
        DispatchQueue.main.async {
            let finalString = NSMutableAttributedString(string: "")
            let titleString = NSMutableAttributedString(string: self.title)
            let space = NSMutableAttributedString(string: " ")
            let imageAttachment = self.attachment
            imageAttachment.image = image
            finalString.append(imageAttachmentString)
            finalString.append(space)
            finalString.append(titleString)
            self.titleLabel.attributedText = finalString
        }
    }
}

} else { titleLabel.text = title }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接