0

I am trying to subclass a UITextView's layoutManager

But keep getting crashes. The examples I have been looking at are in Objective C, so I'm getting a bit confused to how I am supposed to change the layoutManager

Here is my code...

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()

Using...

textView.textContainer.layoutManager = TextWrapLayoutManager()

Compliles but crashes on the next line.

What is the correct way to Subclass UITextView's LayoutManager?

Thanks

Dan
  • 543
  • 2
  • 13
  • It crashes because the textContainer is unowned. So basically your instance dies right after setting it. – Georg Oct 15 '18 at 09:54

1 Answers1

0

Probably your var textContainer is nil.

Use this init

init(frame: CGRect, textContainer: NSTextContainer?)

passing a non nil textContainer.

After that you will be able to set your custom layoutManager

ndPPPhz
  • 315
  • 1
  • 15