gpt4 book ai didi

ios - 围绕 UITextView 创建 CGRect - 高度错误

转载 作者:行者123 更新时间:2023-11-29 05:40:47 25 4
gpt4 key购买 nike

我正在 UITextview 的左侧创建一个与每个段落的高度相匹配的动态列。由于某种原因,我在获得正确的范围高度时遇到问题。我正在使用:

let test = textView.firstRect(for: models.first!.range)

当您继续输入时,它会落后一行。示例:

2行 enter image description here

3行 enter image description here

有什么问题吗?

最佳答案

这是一个示例,文档需要一些帮助......

来自https://developer.apple.com/documentation/uikit/uitextinput/1614570-firstrect :

Return Value

The first rectangle in a range of text. You might use this rectangle to draw a correction rectangle. The “first” in the name refers the rectangle enclosing the first line when the range encompasses multiple lines of text.

事实上,这并不完全正确。

例如,如果您选择文本:

enter image description here

您没有矩形。使用调试 View 层次结构:

enter image description here

很明显,您有两个矩形。

因此,func firstRect(for range: UITextRange) -> CGRect 实际上从 返回第一个矩形包含范围所需的一组矩形

要获取文本范围(例如段落)的实际高度,您需要使用:

let rects = selectionRects(for: textRange)

然后循环遍历返回的 UITextSelectionRect 对象数组。


编辑:

有多种不同的方法可以实现此目的,但这里有一个循环选择矩形并对其高度求和的快速简单示例:

//
// ParagraphMarkerViewController.swift
//
// Created by Don Mag on 6/17/19.
//

import UIKit

extension UITextView {

func boundingFrame(ofTextRange range: Range<String.Index>?) -> CGRect? {

guard let range = range else { return nil }
let length = range.upperBound.encodedOffset-range.lowerBound.encodedOffset
guard
let start = position(from: beginningOfDocument, offset: range.lowerBound.encodedOffset),
let end = position(from: start, offset: length),
let txtRange = textRange(from: start, to: end)
else { return nil }

// we now have a UITextRange, so get the selection rects for that range
let rects = selectionRects(for: txtRange)

// init our return rect
var returnRect = CGRect.zero

// for each selection rectangle
for thisSelRect in rects {

// if it's the first one, just set the return rect
if thisSelRect == rects.first {
returnRect = thisSelRect.rect
} else {
// ignore selection rects with a width of Zero
if thisSelRect.rect.size.width > 0 {
// we only care about the top (the minimum origin.y) and the
// sum of the heights
returnRect.origin.y = min(returnRect.origin.y, thisSelRect.rect.origin.y)
returnRect.size.height += thisSelRect.rect.size.height
}
}

}
return returnRect
}

}

class ParagraphMarkerViewController: UIViewController, UITextViewDelegate {

var theTextView: UITextView = {
let v = UITextView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.font = UIFont.systemFont(ofSize: 17.0)
return v
}()

var paragraphMarkers: [UIView] = [UIView]()

let colors: [UIColor] = [
.red,
.green,
.blue,
.cyan,
.orange,
]

override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(theTextView)

NSLayoutConstraint.activate([

theTextView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 60.0),
theTextView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -60.0),
theTextView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 80.0),
theTextView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),

])

theTextView.delegate = self

// start with some example text
theTextView.text = "This is a single line." +
"\n\n" +
"After two embedded newline chars, this text will wrap." +
"\n\n" +
"Here is another paragraph. It should be enough text to wrap to multiple lines in this textView. As you enter new text, the paragraph marks should adjust accordingly."

}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

// update markers on viewDidAppear
updateParagraphMarkers()
}

func textViewDidChange(_ textView: UITextView) {
// update markers when text view is edited
updateParagraphMarkers()
}

@objc func updateParagraphMarkers() -> Void {

// clear previous paragraph marker views
paragraphMarkers.forEach {
$0.removeFromSuperview()
}

// reset paraMarkers array
paragraphMarkers.removeAll()

// probably not needed, but this will make sure the the text container has updated
theTextView.layoutManager.ensureLayout(for: theTextView.textContainer)

// make sure we have some text
guard let str = theTextView.text else { return }

// get the full range
let textRange = str.startIndex..<str.endIndex

// we want to enumerate by paragraphs
let opts:NSString.EnumerationOptions = .byParagraphs

var i = 0

str.enumerateSubstrings(in: textRange, options: opts) {
(substring, substringRange, enclosingRange, _) in

// get the bounding rect for the sub-rects in each paragraph
if let boundRect = self.theTextView.boundingFrame(ofTextRange: enclosingRange) {

// create a UIView
let v = UIView()

// give it a background color from our array of colors
v.backgroundColor = self.colors[i % self.colors.count]

// init the frame
v.frame = boundRect

// needs to be offset from the top of the text view
v.frame.origin.y += self.theTextView.frame.origin.y

// position it 48-pts to the left of the text view
v.frame.origin.x = self.theTextView.frame.origin.x - 48

// give it a width of 40-pts
v.frame.size.width = 40

// add it to the view
self.view.addSubview(v)

// save a reference to this UIView in our array of markers
self.paragraphMarkers.append(v)

i += 1

}
}

}

}

结果:

enter image description here

关于ios - 围绕 UITextView 创建 CGRect - 高度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56579419/

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