Как я могу центрировать изображение в textView, который присоединен к типу NSTextAttachment? - PullRequest
0 голосов
/ 25 января 2019

У меня есть textView (программно), и я вставил изображение, добавленное к NSTextAttachment, и хочу, чтобы оно было выровнено по центру текстового представления ... но я пока не нашел никаких решений ... Мне было интересноесли эту задачу можно выполнить только с помощью кода ...

    let image = ResizeImage(image: UIImage(named: "logo")!, targetSize: size)

    let image1Attachment = NSTextAttachment()

    image1Attachment.image = image

    let image1Attachments = NSAttributedString(attachment: image1Attachment)

Мой лучший подход к решению проблемы заключается в следующем:

    let image = ResizeImage(image: UIImage(named: "telepaint1")!, 
    targetSize: size)

//let textAttachment = NSTextAttachment()
    let textAttachment = NSTextAttachment()
//let imageStyle = NSMutableParagraphStyle()
    let imageStyle = NSMutableParagraphStyle()
    //imageStyle.alignment = .center
    imageStyle.alignment = .center
    //textAttachment.image = image
    textAttachment.image = image
    let imageText = NSAttributedString(attachment: 
    textAttachment).mutableCopy() as! NSMutableAttributedString
    //attempt to center image...
    let attributedStringToAppend: NSMutableAttributedString = 
    NSMutableAttributedString(attributedString: 
    NSAttributedString(string: "\n\n"))

    //attributedStringToAppend.addAttributes(attr, range: range)

    let combination2: NSMutableAttributedString = 
    NSMutableAttributedString(attributedString: 
    NSAttributedString(string: "\n\n"))


    combination2.append(lineBreak)
    // combination2.addAttribute(attr, range: NSRange(location: 0, 
    length: length))

    combination2.append(imageText)
    //this text will display the "Walktrough" text on image 

    combination2.append(attributedText)

    tv.attributedText = combination2

1 Ответ

0 голосов
/ 27 января 2019

enter image description here Ответ (работал для меня!):

    let paragraphStyle = NSMutableParagraphStyle()

    paragraphStyle.alignment = .center

    attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: length))

    let size = CGSize(width: 100, height: 100)


    //Here is an attempt to resize image and center it...



    let image = ResizeImage(image: UIImage(named: "logo")!.withRenderingMode(.alwaysTemplate), targetSize: size)


    let textAttachment = NSTextAttachment()


    let imageStyle = NSMutableParagraphStyle()


    imageStyle.alignment = .center


    textAttachment.image = image


    let imageText = NSAttributedString(attachment: textAttachment).mutableCopy() as! NSMutableAttributedString

    let length2 = imageText.length

    imageText.addAttribute(NSAttributedString.Key.paragraphStyle, value: imageStyle, range: NSRange(location: 0, length: length2))
...