0

我正在尝试将 a 子类UITextViewlayoutManager

但不断出现崩溃。我一直在看的例子是在Objective C中,所以我对我应该如何更改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()

使用...

textView.textContainer.layoutManager = TextWrapLayoutManager()

编译但在下一行崩溃。

子类 UITextView 的 LayoutManager 的正确方法是什么?

谢谢

4

1 回答 1

0

可能你var textContainernil

使用这个初始化

init(frame: CGRect, textContainer: NSTextContainer?)

传递一个非零文本容器。

之后,您将能够设置您的自定义layoutManager

于 2018-09-09T22:01:11.157 回答