如何在与NSTextAttachment类型相连的textView上居中放置图像?

时间:2019-01-25 17:34:35

标签: swift nstextattachment

我有一个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 :(得分:0)

enter image description here答案(为我工作!):<​​/ p>

    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))