Swift UITextView подкласс LayoutManager - PullRequest
0 голосов
/ 09 сентября 2018

Я пытаюсь создать подкласс UITextView layoutManager

Но продолжайте получать сбои. Примеры, которые я рассмотрел, приведены в 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()

Компилируется, но вылетает на следующей строке.

Как правильно использовать LayoutManager для UITextView подкласса?

Спасибо

1 Ответ

0 голосов
/ 10 сентября 2018

Вероятно, ваш var textContainer равен nil.

Используйте этот init

init(frame: CGRect, textContainer: NSTextContainer?)

передача не ноль textContainer.

После этого вы сможете установить свой собственный layoutManager

...