Search code examples
iosobjective-cswifttextkit

How to build a rich text view like Medium iOS app using Text Kit?


Medium iOS App Screenshot

It's a rich text view, with multiple images(variant height) among the text, and each of them sits between two paragraphs. Please refer to the screenshot.

I know that Text Kit supports exclusion paths, is it possible to build such a rich text view based on this technology? And how do you determine the position of the images when creating the exclusion paths?

Thanks in advance.


Solution

  • You don't need an exclusion path because don't want to wrap the text around the image's shape. You just want the image to appear as its own centered paragraph. That means you need newlines (\n) before and after the image attachment, and you need to set a paragraph style with alignment = .Center on the attachment.

    Example:

    import UIKit
    import XCPlayground
    
    let richText = NSMutableAttributedString(string: "Hello!\n")
    let attachment = NSTextAttachment(data: nil, ofType: nil)
    attachment.image = UIImage(named: "Kaz-256.jpg")
    let imageText = NSAttributedString(attachment: attachment).mutableCopy() as! NSMutableAttributedString
    let imageStyle = NSMutableParagraphStyle()
    imageStyle.alignment = .Center
    imageText.addAttribute(NSParagraphStyleAttributeName, value: imageStyle, range: NSMakeRange(0, imageText.length))
    richText.appendAttributedString(imageText)
    richText.appendAttributedString(NSAttributedString(string: "\nGoodbye."))
    
    
    let textView = UITextView(frame: CGRectMake(0, 0, 320, 480))
    textView.attributedText = richText
    XCPlaygroundPage.currentPage.liveView = textView
    

    Result:

    example result