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

How to break selection by paragraphs (Medium like) in an iOS App?

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

在这种情况下你只能select文本“你有义务。

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

如果我正确理解你的问题,我会尝试为每个段落创建一个 UITextView 并正确定位它们。当用户按下回车键时创建一个新视图(并确保保留光标后的文本),如果他们按下删除键且光标位于第二个视图的开头,则加入两个相邻视图的内容。

这样,selection 将在每个视图中工作,但用户不能 select 同时跨两个视图。

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
    }
}