Swift UITextView LayoutManager子类

时间:2018-09-09 19:24:05

标签: swift uitextview subclass nslayoutmanager

我正在尝试将UITextView的{​​{1}}子类化

但是请继续崩溃。我一直在看的示例是在Objective C中进行的,所以我对应该如何更改layoutManager感到有些困惑

这是我的代码...

layoutManager

}

class TextWrapLayoutManager: NSLayoutManager {

override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
    self.enumerateLineFragments(forGlyphRange: NSMakeRange(0, self.numberOfGlyphs)) { (rect, usedRect, textContainer, glyphRange, Bool) in
        let lineBoundingRect = self.boundingRect(forGlyphRange: glyphRange, in: textContainer)
        let adjustedLineRect = lineBoundingRect.offsetBy(dx: origin.x + 5, dy: origin.y + 2)
        let fillColorPath: UIBezierPath = UIBezierPath(roundedRect: adjustedLineRect, cornerRadius: 10)
        UIColor.red.setFill()
        fillColorPath.fill()
    }
}

使用...

let textView = UITextView(frame: CGRect(x: 0, y: canvasView.center.y - 50, width: UIScreen.main.bounds.width, height: 130))

    textView.textContainer.layoutManager = TextWrapLayoutManager()

    textView.keyboardAppearance = .dark
    textView.textAlignment = .center
    textView.font = UIFont.attrctFont(ofSize: 32, weight: .bold)
    textView.textColor = textColor
    textView.layer.cornerRadius = 10
    textView.layer.masksToBounds = true
    textView.textContainerInset = UIEdgeInsets(top: 2, left: 5, bottom: 2, right: 5)
    textView.tintColor = .white
    textView.isScrollEnabled = false
    textView.delegate = self
    self.canvasView.addSubview(textView)

    addGestures(view: textView)
    textView.becomeFirstResponder()

可以,但是在下一行崩溃。

继承UITextView的LayoutManager的正确方法是什么?

谢谢

1 个答案:

答案 0 :(得分:0)

您的var textContainer可能是nil

使用此初始化

init(frame: CGRect, textContainer: NSTextContainer?)

传递 non nil textContainer。

之后,您将可以设置自定义layoutManager