Swift:如何在字符串中的特定索引处插入UIImage?

时间:2016-03-27 15:48:50

标签: ios swift uiimageview uiimage

我正在尝试将UIImageView插入textView ..它可以工作,但我的图像的位置始终位于textView的角落。 这是我的代码:

if(parseur.textStrings.containsString(SymboleList[i])){
   let image = UIImageView(image: UIImage(named: imagesSymboleList[i]))
   let path = UIBezierPath(rect: CGRectMake(0,0, image.frame.width,       image.frame.height))
   parseur.textStrings.stringByReplacingOccurrencesOfString(SymboleList[i], withString: "")             
   boiteTexte.textContainer.exclusionPaths = [path]
   boiteTexte.addSubview(image)
}

SymboleList是一个包含我想用图像替换的字符串的列表(图像在imagesSymboleList中) 我必须找到我要替换的字符串的位置并在该索引处插入我的图像。 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

以下是如何实现图像的类似图像插入的方法

@IBOutlet var textView: UITextView!

var SymboleList: [String] = ["ipsum", "incididunt", "Excepteur"];
var imagesSymboleList: [String] = ["img.png", "img.png", "img.png"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.insertImages();
}

func insertImages() {

    let attrString: NSMutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)
    let style = NSMutableParagraphStyle()
    style.maximumLineHeight = (textView.font?.lineHeight)!
    attrString.addAttribute(
        NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, attrString.length))

    for var i = 0; i < SymboleList.count; i++ {

        // get attachment image
        var image = UIImage(named: imagesSymboleList[i])
        let scaleFactor = (textView.font?.lineHeight)! / (image?.size.height)!
        let newSize = CGSizeMake((image?.size.width)! * scaleFactor, (image?.size.height)! * scaleFactor)
        image = self.scaleImage(image!, newSize: newSize)
        let attachment: NSTextAttachment = NSTextAttachment()
        attachment.image = image;

        // build attachment string
        let attachmentString: NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        attachmentString.addAttribute(
            NSBaselineOffsetAttributeName,
            value: -(textView.font?.lineHeight)! / 4,
            range: NSMakeRange(0, attachmentString.length))

        // replace text with images
        let range = (attrString.string as NSString).rangeOfString(SymboleList[i])
        attrString.replaceCharactersInRange(range, withAttributedString: attachmentString)

    }

    textView.attributedText = attrString

}

func scaleImage(image: UIImage, newSize: CGSize) -> UIImage {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

<强>结果
Result