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

时间:2019-06-13 11:27:39

标签: ios swift uitextview

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

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

在您继续输入时,一行后面紧跟着一行。例子:

2行 enter image description here

3行 enter image description here

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用下面的代码,您将获得正确的文本视图内容大小。

let newSize = self.textView.sizeThatFits(CGSize(width: self.textView.frame.width, height: CGFloat.greatestFiniteMagnitude))
        print("\(newSize.height)")

根据此高度更改动态列的高度。如果要在用户键入时更改列高,请使用UITextViewDelegate方法textViewDidChange来完成。

希望这会有所帮助。

答案 1 :(得分:0)

这是一个示例,文档可以使用一些帮助...

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

  

返回值

     

文本范围内的第一个矩形。您可以使用此矩形绘制校正矩形。名称中的“第一”是指范围包含多行文本时包围第一行的矩形。

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

例如,如果您选择文本:

enter image description here

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

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