ios 如何在UIScrollView中通过编程高亮显示和滚动UITextView?

kxeu7u2r  于 2023-03-05  发布在  iOS
关注(0)|答案(1)|浏览(145)

目前,我有一个UITextView(禁用滚动-UITextView inside UIScrollView with AutoLayout
在一个UIScrollView里面。
我们希望通过编程突出显示选定的文本。这就是我们所做的。

@IBAction func click(_ sender: Any) {
    let attributedText = textView.attributedText!
    
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
    
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.removeAttribute(NSAttributedString.Key.backgroundColor, range: range)
    
    let searchedString = "Can you highlight and scroll?"
    
    do {
        let regex = try NSRegularExpression(
            pattern: NSRegularExpression.escapedPattern(for: searchedString),
            options: .caseInsensitive
        )
        
        let targetedString = attributedString.string
        
        for match in regex.matches(in: targetedString, options: .withTransparentBounds, range: range) {
            print(">>>> found the 1st match")
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
            break
        }
    } catch {
        print("\(error)")
    }
    
    textView.attributedText = attributedString
}

其工作原理如以下视频所示。

除了手动滚动,我们还喜欢通过编程方式执行滚动,以使突出显示的文本可见。
请注意,执行以下代码将无法实现我们想要的效果

textView.scrollRangeToVisible(match.range)
  • 这是因为在UITextView中禁用了滚动 *

我想知道,什么是一个适当的方式,我执行突出显示和滚动UITextView内的UIScrollView?
演示:https://github.com/yccheok/programming-issue/tree/main/highlight-and-scroll/demo

toe95027

toe950271#

你可以这样做,在textView layoutManager上使用boundingRect(forGlyphRange:in:)来获取特定范围的矩形,然后使用scrollView滚动到特定的矩形。

import UIKit

class ViewController: UIViewController {
    var button = UIButton()
    var textView = UITextView()
    let scrollView = UIScrollView()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .black
    scrollView.backgroundColor = .clear
    textView.backgroundColor = .clear
    
    view.addSubview(scrollView)
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        scrollView.topAnchor.constraint(equalTo: view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor),
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
    ])
    
    
    textView.isScrollEnabled = false
    textView.isEditable = false
    textView.clipsToBounds = true
    
    textView.translatesAutoresizingMaskIntoConstraints = false
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Button", for: .normal)
    button.backgroundColor = .red
    button.addTarget(self, action: #selector(buttonCLicked), for: .touchUpInside)
    scrollView.addSubview(button)
    scrollView.addSubview(textView)
    
    
    NSLayoutConstraint.activate([
        button.topAnchor.constraint(equalTo: scrollView.topAnchor),
        button.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
        button.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
        button.heightAnchor.constraint(equalToConstant: 44),
        
        textView.topAnchor.constraint(equalTo: button.bottomAnchor),
        textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
        textView.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
        textView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
        textView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1)
    ])
    
    
    let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident,\n\n\n Can you highlight and scroll? \n\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of sometimes on purpose (injected humour and the like)."
    
    
    
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(string: text))
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20)], range: range)
    
    textView.attributedText = attributedString

    
}

@objc func buttonCLicked() {
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText!)
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20)], range: range)
    
    let searchedString = "Can you highlight and scroll?"
    var machedRange:NSRange?
    do {
            let regex = try NSRegularExpression(
                pattern: NSRegularExpression.escapedPattern(for: searchedString),
                options: .caseInsensitive
            )
            
            let targetedString = attributedString.string
            
            for match in regex.matches(in: targetedString, options: .withTransparentBounds, range: range) {
                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
                attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: match.range)
                
                machedRange = match.range

                break
            }
        } catch {
            print("\(error)")
        }
    
    textView.attributedText = attributedString
    guard let machedRange else {return}
    let buttonHeight:CGFloat = 44
    let margin:CGFloat = 100
    let rect = self.textView.layoutManager.boundingRect(forGlyphRange: machedRange, in: self.textView.textContainer)
    self.scrollView.scrollRectToVisible(CGRect(x: rect.minX, y: rect.minY + buttonHeight + margin, width: rect.width, height: rect.height), animated: true)
    
    
   }

}

抱歉gif太小,无法放大:D

相关问题