2016-07-20 25 views
2

Ich mache eine Notiz App, aber ich geriet in Schwierigkeiten.Wie kann ich ein Bild in UITextView hinzufügen?

Ich möchte ein Bild in UITextView setzen. Ich benutzen NSAttributedString das Bild in UITextView zu setzen aber wenn ich Bild gesetzt von der imagepicker, die Bildgröße zu groß ist wie dieses

image

ich es wie der Apfel machen will Notizen App

image2

Wie kann ich das beurteilen?

let images = selectedImage 
    let attachment = NSTextAttachment() 

    attachment.image = images 

    let attString = NSAttributedString(attachment: attachment) 

    textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location) 

Antwort

2

Dies könnte

let textView = UITextView(frame: CGRectMake(50, 50, 200, 300)) 
let attributedString = NSMutableAttributedString(string: "before after") 
let textAttachment = NSTextAttachment() 
textAttachment.image = UIImage(named: "sample_image.jpg")! 

let oldWidth = textAttachment.image!.size.width; 

let scaleFactor = oldWidth/(textView.frame.size.width - 10); //for the padding inside the textView 
textAttachment.image = UIImage(CGImage: textAttachment.image!.CGImage, scale: scaleFactor, orientation: .Up) 
var attrStringWithImage = NSAttributedString(attachment: textAttachment) 
attributedString.replaceCharactersInRange(NSMakeRange(6, 1), withAttributedString: attrStringWithImage) 
textView.attributedText = attributedString; 
self.view.addSubview(textView) 
+0

Dank Ihnen nützlich sein! Es klappt!! aber wenn ich ** NSAttributedString ** zu ** NSUserDefaults ** speichere und wenn ich wieder lade, ist die Bildgröße wieder groß !! – Daniel

+0

@Daniel .. Ich habe auch das gleiche Problem. Was war die Lösung? – iOS

+0

Siehe diese Antwort http://stackoverflow.com/a/30417310/2564702 –