Search code examples
htmliosobjective-cnsattributedstringoutline

How to make a box around a paragraph of NSAttributedString


In HTML you can make a paragraph that has a red outline (or a dotted outline).

http://www.w3schools.com/cssref/tryit.asp?filename=trycss_outline

I was wondering if something similar can be done using NSAttributedStrings. I am not looking to outline each character, I am looking to place the entire chunk of inside a box and that box would have a border. Is this possible with NSAttributedString or even CoreText?

I have see this (How to draw a border around a paragraph in UILabel?) solution, but I don't want to add a layer on top of the text, I would rather have it be a part of the text.


Solution

  • Sounds like you'll want a UITextView subclass with some custom drawing. Here's some code for a playground that should do the trick. You can tweak the details to get it looking how you like, but this is the basic idea.

    And here's a cheatsheet for custom drawing that I always use: http://www.techotopia.com/index.php/An_iOS_7_Graphics_Tutorial_using_Core_Graphics_and_Core_Image

    import UIKit
    import XCPlayground
    
    let container = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    container.backgroundColor = UIColor(white: 0.95, alpha: 1.0 )
    XCPShowView( "Container", container )
    
    class DottedTextView: UITextView {
    
        override func drawRect(rect: CGRect) {
    
            let context = UIGraphicsGetCurrentContext()
            CGContextSetLineWidth( context, 20.0 )
            CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
            let dashArray: [CGFloat] = [ 6, 4 ]
            CGContextSetLineDash( context, 3, dashArray, dashArray.count )
            CGContextStrokeRect( context, rect )
        }
    
    }
    
    let textView = DottedTextView(frame: CGRect(x: 20, y: 20, width: 300, height: 200) )
    container.addSubview( textView )
    textView.text = "Bacon ipsum dolor amet ball tip kielbasa brisket drumstick pastrami pork chicken shankle. Ribeye cow doner shankle, alcatra pork chop flank corned beef t-bone shoulder prosciutto."
    

    enter image description here