如何将 UITextView
中的段落分隔成完全独立的文本簇,例如在进行选择时只能选择该段落中的单词?
在这种情况下,您只能选择文本“You obliged.”
我正在尝试在段落外取消选择,进行所需的数学运算来定义段落范围,但到目前为止运气不好。
最佳答案
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/