2017-03-08 27 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) 

也許我必須添加一箇中間步驟,我得到完整的字符串,然後在其上應用範圍?

+0

的http://計算器。 COM /問題/ 14024124 /獲取選擇高亮顯示的文本字符串-from-nstextview-objective-c –

+0

謝謝Mitesh,但是我在Swift中編程而不是Objective-C。 – Cue

回答

1

什麼

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

編輯:

這應該現在的工作:

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

相關問題