境界内のテキストだけをプログラムで選択し、ウィンドウがスクロールまたは境界を変更するときにそれを変更する方法が必要です。
SelectAll
動作しないでしょう。ドキュメント全体は必要ありません。私の目標は、ウィンドウにスクロールして表示されるテキストに反応し、それをスキャンしてキーワードを探し、コンテキスト情報を 2 番目のウィンドウに表示することです。
境界内のテキストだけをプログラムで選択し、ウィンドウがスクロールまたは境界を変更するときにそれを変更する方法が必要です。
SelectAll
動作しないでしょう。ドキュメント全体は必要ありません。私の目標は、ウィンドウにスクロールして表示されるテキストに反応し、それをスキャンしてキーワードを探し、コンテキスト情報を 2 番目のウィンドウに表示することです。
確かに、ちょっとしたハックである解決策を思いつきました。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)
}
}
}