2017-03-08 18 views
0

Swift의 NSTextView에서 선택한 문자열을 가져 오는 방법?Swift의 NSTextView에서 선택한 문자열을 가져 오는 방법은 무엇입니까?

// create a range of selected text 
let range = mainTextField.selectedRange() 

// this works but I need a plain string not an attributed string 
let str = mainTextField.textStorage?.attributedSubstring(from: range) 

어쩌면 전체 문자열을 얻은 다음 중간 범위를 추가해야 할 수도 있습니다.

이 지금 작동합니다 :

let str = mainTextField.text.substring(with: range) 

에 대해 편집 무엇

+0

에 http : // 유래. co.kr/questions/14024124/get-selection-highlighted-text-string -from-nstextview-objective-c –

+0

Mitesh에게 감사드립니다. 그러나 Objective-C가 아닌 Swift에서 프로그래밍하고 있습니다. – Cue

답변

1

let range = mainTextField.selectedRange()  // Returns NSRange :-/ (instead of Range) 
let str = mainTextField.string as NSString? // So we cast String? to NSString? 
let substr = str?.substring(with: range)  // To be able to use the range in substring(with:) 
+0

고맙습니다. 잘 작동합니다. – Cue

0

이 당신을 위해 도움이 될 수 있습니다

let textView = NSTextView(frame: NSMakeRect(0, 0, 100, 100)) 
let attributes = [NSForegroundColorAttributeName: NSColor.redColor(), 
       NSBackgroundColorAttributeName: NSColor.blackColor()] 
let attrStr = NSMutableAttributedString(string: "my string", attributes: attributes) 
let area = NSMakeRange(0, attrStr.length) 
if let font = NSFont(name: "Helvetica Neue Light", size: 16) { 
    attrStr.addAttribute(NSFontAttributeName, value: font, range: area) 
    textView.textStorage?.appendAttributedString(attrStr) 
} 
+0

Mitesh, 내 도구 상자에이 코드 스 니펫을 갖는 것이 매우 유용합니다! – Cue