2017-03-08 12 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:// stackoverflowの。 com/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

関連する問題