2011-02-01 125 views

回答

7

的第一件事是讓富文本支持,您可以通過檢查做到這一點無論是在Interface Builder中「富文本「選項或通過使用setAllowsEditingTextAttributes:的代碼。

然後就是關於NSAttributedString s。

雖然很大的問題是,看起來你需要對選定的文本應用更改。這不適用於NSTextField。僅與NSTextView s。

如果你可以改變它,繼續前進,它會讓事情變得更容易。但是,如果您確實需要使用NSTextField,則可能需要訪問現場編輯器。每個窗口都有一個關聯的,這是在幕後處理文本的過程。

NSTextView *editor = (NSTextView *)[window fieldEditor:YES forObject:myTextField] 

然後你可以愉快地調用NSTextView的方法setSelectedTextAttributes:

瞭解更多關於字段編輯器here at Applein CocoaDev

1

假設你的NSTextField *是文本框,下面的代碼強調了選擇:

NSMutableAttributedString * as = [[[textField attributedStringValue] mutableCopy] autorelease]; 
[as beginEditing]; 
[as addAttribute:NSUnderlineStyleAttributeName 
      value:[NSNumber numberWithInt:NSUnderlineStyleSingle] 
      range:[[[textField window] fieldEditor:YES forObject:textField] selectedRange]]; 

[as endEditing]; 
[textField setAttributedStringValue:as]; 
+0

但是,強調前三個字符,而不是選擇。 (另外,爲什麼不使用`[[[[textField attributedStringValue] mutableCopy] autorelease]`?)我想知道,你可以問外業編輯選擇什麼嗎? – 2011-02-01 15:16:26

+0

@彼得:謝謝。 :-) – diciu 2011-02-01 15:44:06

相關問題