How to add an image/button to a UITextView? With auto line break?
I want to add an image/button to my UITextView and the text should automatically make a line break that the image/button fits.
Second question. I want to make a button called "move image/button" and then the user开发者_StackOverflow can move the image/button through the UITextView and the text should adjust
.
PS: like in "Pages" for mac or "Word" for Windows
This is decidedly non-trivial. For starters, you can't simply embed a UIImage inside a UITextView and even if you could text wouldn't magically flow around it. What you'll need to do is create your own object based on a UITextView that substantially extends its capabilities to provide such editing tools.
For a heads-up as to what you're getting into you might want to take a look at the example Text Editor source code from the Omni Group.
Use the attributedText
property of UITextView
with an NSAttributedString
with NSTextAttachment
with image. Note that the UITextView
must be Selectable
(in Storyboard).
Swift demonstration:
let attributedImage = NSAttributedString(with: #imageLiteral(resourceName: "myImage"))
let attributedText = NSMutableAttributedString(string: "Hello ")
attributedText.append(attributedImage)
textView.attributedText = attributedText
Where the attributedImage
is built from those convenience initializers:
extension NSAttributedString {
convenience init(with image: UIImage) {
self.init(attachment: NSTextAttachment(with: image))
}
}
extension NSTextAttachment {
convenience init(with image: UIImage) {
self.init()
self.image = image
// adjust origin if needed
self.bounds = CGRect(origin: .zero, size: image.size)
}
}
This solution works for: iOS 7.0, macOS 10.11, tvOS 9.0, *.
精彩评论