Я придумал решение, которое, по общему признанию, является чем-то вроде взлома. Он оценивает начальный и конечный индекс видимого текста, используя смещение содержимого, высоту содержимого и высоту фрейма содержимого textView. Ответ является только оценочным, потому что перенос слов непредсказуем. Результат обычно составляет ±10 символов реального видимого текста. Вы можете компенсировать это, добавив/вычитая буфер из нескольких символов к начальным/конечным смещениям, что гарантирует, что у вас есть подстрока вашего текста textView, которая определенно содержит видимый текст, только с несколькими дополнительными символами в начале и конец.
Я надеюсь, что этот ответ поможет или, по крайней мере, вдохновит вас (или кого-то еще) на поиск решения, которое точно удовлетворит ваши потребности.
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var textView: UITextView!
let textViewText = "Here's to the crazy ones. The misfits. The rebels. The trouble-makers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules, and they have no respect for the status-quo. You can quote them, disagree with them, glorify, or vilify them. But the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do."
override func viewDidLoad() {
super.viewDidLoad()
textView.text = textViewText
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let textViewContentHeight = Double(textView.contentSize.height)
let textViewFrameHeight = Double(textView.frame.size.height)
let textViewContentOffset = Double(textView.contentOffset.y)
let textViewCharacterCount = textViewText.characters.count
let startOffset = Int((textViewContentOffset / textViewContentHeight) * Double(textViewCharacterCount))
// If the user scrolls quickly to the bottom so that the text is completely off the screen, we don't want to proceed
if startOffset < textViewCharacterCount {
let endIndex = Int(((textViewContentOffset + textViewFrameHeight) / textViewContentHeight) * Double(textViewCharacterCount))
var endOffset = endIndex - textViewCharacterCount
if endIndex > textViewCharacterCount {
endOffset = 0
}
let visibleString = textViewText.substringWithRange(textViewText.startIndex.advancedBy(startOffset)..<textViewText.endIndex.advancedBy(endOffset))
print(visibleString)
}
}
}
person
Austin Wood
schedule
16.09.2016