ios - 如何在 iOS 应用程序中按段落(中等)中断选择?

标签 ios objective-c swift uitextview nsattributedstring

如何将 UITextView 中的段落分隔成完全独立的文本簇,例如在进行选择时只能选择该段落中的单词?

在这种情况下,您只能选择文本“You obliged.

enter image description here

我正在尝试在段落外取消选择,进行所需的数学运算来定义段落范围,但到目前为止运气不好。

最佳答案

The idea is to locate extension of current paragraph from cursor position when starting to select the text. Then allow only the intersection between ranges of the paragraph and the one corresponding to the selection.


这是 Swift 3 的解决方案


class RichTextView: UITextView {...}

extension RichTextView: UITextViewDelegate {

  func textViewDidChangeSelection(_ textView: UITextView) {
    let range = textView.selectedRange
    if range.length > 0 {
     if let maxRange = 
       textView.attributedText.getParagraphRangeContaining(cursorPosition: range.location){
          selectedRange = NSIntersectionRange(maxRange, range)
      }
    }
  }
}

extension NSAttributedString {

    func getParagraphRangeContaining(cursorPosition: Int) -> NSRange? {
        let cursorPosition = cursorPosition - 1

        let nsText = self.string as NSString
        let textRange = NSMakeRange(0, nsText.length)

        var resultRange : NSRange?
        nsText.enumerateSubstrings(in: textRange, options: .byParagraphs, using: {
            (substring, substringRange, _, _) in

            if (NSLocationInRange(cursorPosition , substringRange)) {
                resultRange = substringRange
                return
            }
        })
        return resultRange
    }
}

关于ios - 如何在 iOS 应用程序中按段落(中等)中断选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042204/

相关文章:

ios - NSDateFormatter 不起作用

iphone - 导航栏不见了

ios - 当添加到另一个对象中时,对象中的 Double 转换为字符串

ios - 如何在 iOS 11 中隐藏章节标题?

swift - config.preparations.append(modelName.self) 错误使用未解析的标识符 'modelName'

iphone - 在 WebView 或浏览器中启动存储的 html 页面 - Objective C/Xcode

iphone - 如何调用具有多个参数的方法

objective-c - OSX 上自动更新应用程序的常见更新程序?

ios - 体系结构 i386 的 undefined symbol 和未找到体系结构 i386 的符号

ios - 键值编码说明