如何在一段 NSAttributedString 周围制作一个框

How to make a box around a paragraph of NSAttributedString

在 HTML 中,您可以创建一个具有红色轮廓(或虚线轮廓)的段落。

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

我想知道是否可以使用 NSAttributedStrings 完成类似的事情。我不想勾勒出每个字符,我希望将整个块放在一个盒子里,那个盒子会有一个边框。这对 NSAttributedString 甚至 CoreText 是否可行?

我看过这个(How to draw a border around a paragraph in UILabel?)解决方案,但我不想在文本之上添加一层,我宁愿让它成为文本的一部分。

听起来您需要一个带有一些自定义绘图的 UITextView 子类。这是一些应该可以解决问题的游乐场代码。您可以调整细节以使其看起来像您喜欢的样子,但这是基本想法。

这是我经常使用的自定义绘图备忘单: 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."