我有以下 UITextView 子类:
class CustomTextView: UITextView {
required init?(coder: NSCoder) {
super.init(coder: coder)
customInit()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
customInit()
}
func customInit(){
contentMode = .redraw
isSelectable = true
isEditable = false
isScrollEnabled = false
let padding = textContainer.lineFragmentPadding
textContainerInset = UIEdgeInsets(top: 0, left: -padding, bottom: 0, right: -padding)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let range = NSRange(location: 10, length: 5)
let beginning = beginningOfDocument
let start = position(from: beginning, offset: range.location)
let end = position(from: start!, offset: range.length)
let textRange = textRange(from: start!, to: end!)
let frames = selectionRects(for: textRange!)
print("draw!!! \(frames.first?.rect)") // after scrolling, this prints: draw!!! Optional((inf, inf, 0.0, 0.0))
frames.forEach { frame in
let bpath = UIBezierPath(rect: frame.rect)
UIColor.red.set()
bpath.stroke()
}
}
}
这个
CustomTextView
在UITableView
的每个单元格中,属性文本设置如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
cell.myTextView.attributedText = items[indexPath.row].0
cell.layoutIfNeeded()
cell.myTextView.setNeedsDisplay()
print("setNeedsDisplay!!!")
return cell
}
第一次显示表格时,它工作正常。但是,滚动后显示的每个单元格不再具有矩形。经过一些调试,我发现滚动后从
selectionRects(for: textRange!)
返回的rects都是无效的,rect中有infinite
值。滚动后,打印:
draw!!! Optional((inf, inf, 0.0, 0.0))
我做错了什么?
屏幕截图(注意底部的几个单元格中没有红色块):