gpt4 book ai didi

Swift UITextView LayoutManager 子类

转载 作者:行者123 更新时间:2023-11-30 11:10:25 27 4
gpt4 key购买 nike

我正在尝试对 UITextViewlayoutManager 进行子类化

但不断发生崩溃。我一直在看的示例是 Objective C 中的,所以我对如何更改布局管理器感到有点困惑

这是我的代码...

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 的正确方法是什么?

谢谢

最佳答案

可能你的var textContainernil

使用这个初始化

init(frame: CGRect, textContainer: NSTextContainer?)

传递一个非零文本容器。

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

关于Swift UITextView LayoutManager 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52247924/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com