羅布的答案,寫在斯威夫特。我已經添加了一些安全檢查。
private func visibleRangeOfTextView(textView: UITextView) -> NSRange {
let bounds = textView.bounds
let origin = CGPointMake(10,10) //Overcome the default UITextView left/top margin
let startCharacterRange = textView.characterRangeAtPoint(origin)
if startCharacterRange == nil {
return NSMakeRange(0,0)
}
let startPosition = textView.characterRangeAtPoint(origin)!.start
let endCharacterRange = textView.characterRangeAtPoint(CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds)))
if endCharacterRange == nil {
return NSMakeRange(0,0)
}
let endPosition = textView.characterRangeAtPoint(CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds)))!.end
let startIndex = textView.offsetFromPosition(textView.beginningOfDocument, toPosition: startPosition)
let endIndex = textView.offsetFromPosition(startPosition, toPosition: endPosition)
return NSMakeRange(startIndex, endIndex)
}
更新了夫特4:
private func visibleRangeOfTextView(textView: UITextView) -> NSRange {
let bounds = textView.bounds
let origin = CGPoint(x: 10, y: 10) //Overcome the default UITextView left/top margin
let startCharacterRange = textView.characterRange(at: origin)
if startCharacterRange == nil {
return NSRange(location: 0, length: 0)
}
let startPosition = textView.characterRange(at: origin)?.start
let endCharacterRange = textView.characterRange(at: CGPoint(x: bounds.maxX, y: bounds.maxY))
if endCharacterRange == nil {
return NSRange(location: 0, length: 0)
}
let endPosition = textView.characterRange(at: CGPoint(x: bounds.maxX, y: bounds.maxY))!.end
let startIndex = textView.offset(from: textView.beginningOfDocument, to: startPosition!)
let endIndex = textView.offset(from: startPosition!, to: endPosition)
return NSRange(location: startIndex, length: endIndex)
}
實施例的使用,從一個按鈕抽頭稱爲:
@IBAction func buttonTapped(sender: AnyObject) {
let range = visibleRangeOfTextView(self.textView)
// Note: "as NSString" won't work correctly with Emoji and stuff,
// see also: http://stackoverflow.com/a/24045156/1085556
let nsText = self.textView.text as NSString
let text = nsText.substringWithRange(range)
NSLog("range: \(range), text = \(text)")
}
尼斯。爲了提高效率,通過從頭開始移動長度字符來發現結局 - 從文檔的開頭開始一直很慢,但提前便宜。 – 2012-02-17 10:12:21
當你說,「這樣的事情應該工作」,你真的嘗試過嗎?這幾乎是我實際可視文本範圍的三倍。謝謝。 – 2014-08-01 15:56:43
@JasonTyler [這是一個包含測試應用程序的回購。](https://github.com/mayoff/textview-visible-range)對我很好用。可能需要Xcode 6。 – 2014-08-01 16:48:34