2016-09-16 9 views
0

나는 방법으로 경계에서 텍스트를 프로그래밍 방식으로 선택하고 창이 스크롤되거나 바운드가 변경 될 때 해당 변경 사항을 적용하고 싶습니다.NSTextView에서 볼 수있는 모든 텍스트를 선택하는 방법은 무엇입니까?

SelectAll은 작동하지 않습니다. 나는 전체 문서를 원하지 않는다. 제 목표는 창에서 스크롤되는 텍스트에 반응하여 핵심 단어를 스캔하고 두 번째 창에 컨텍스트 정보를 표시하는 것입니다.

+0

나는 모든 접근법에 대해 설명했지만 여기서는 설명하지 않았습니다. 범위 내에서 선 조각을 볼 수있는 방법이 있다면 발견하지 못했습니다. – johnrubythecat

답변

0

필자는 솔직히 해킹 해법을 제시했습니다. 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) 
     } 
    } 
} 
+0

나는 그것을 즉시 시도 할 것이다. 또한 : 나는 이런 생각이 다른 대답이다. (NSRange) glyphRangeForBoundingRectWithoutAdditionalLayout : (CGRect) bounds inTextContainer : (NSTextContainer *) container; 문자 모양 색인을 사용하여 문자 색인 범위에 액세스하십시오. 계속 작업하고 성공하면 게시 할 것입니다. 위서 주셔서 감사합니다. – johnrubythecat

+0

여기에 관심있는 이전 게시물입니다. http://stackoverflow.com/questions/16675997/using-nsglyph-and-memory-allocation – johnrubythecat