Как разместить изображение внутри UILabel в начале текста UILabel? - PullRequest
2 голосов
/ 03 июля 2019

Привет, я хочу добавить изображение круглой точки к некоторой 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 Ответ

1 голос
/ 03 июля 2019

Я получил его на работу. Проблема заключалась в том, что я устанавливал текст в раскадровке (.xib). Таким образом, это расширение не изменило изображение на фронт, даже если bool-val был ложным.

Просто установите текст из вызова функции, и значение 'false' приведет к тому, что изображение будет установлено в начале метки.

Пример1 (что я сделал не так):

// 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!

Example2 (что заставило его работать!):

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!
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...