2010-08-23 20 views
0

我在NSMatrix中顯示按鈕。NSMatrix中NSButtonCell中的文本顯示圖像

我的要求是:

改變按鈕標題和 發生在標題的開頭圖像的色彩,當某些條件得到滿足。

要做到這一點,我用下面的代碼:

// setting attributed text 
      NSAttributedString *selectedCellAttribute; 

      NSFont *selectedCellFont = [NSFont fontWithName:@"Lucida Grande" size:11]; 
      NSColor *selectedCellColor = [NSColor redColor]; 
      NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
      [style setAlignment:NSCenterTextAlignment]; 

      // setting image 
      NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init]; 
      NSCell *cell = [imageAttachment attachmentCell]; 
      [cell setImage:[NSImage imageNamed:@"caution_small.png"]]; 

      NSDictionary *selectedCellDictionary = [NSDictionary dictionaryWithObjectsAndKeys:imageAttachment,NSAttachmentAttributeName,selectedCellFont,NSFontAttributeName,selectedCellColor,NSForegroundColorAttributeName,style,NSParagraphStyleAttributeName,nil]; 

      // recognizing cell 

      NSButtonCell *associatedCell = [associatesMatrix cellAtRow:0 column:2]; 
      selectedCellAttribute = [[NSAttributedString alloc] initWithString:[associatedCell title] attributes:selectedCellDictionary]; 
      [associatedCell setAttributedTitle:selectedCellAttribute]; 

雖然上面的代碼顯示標題的顏色變化,這是沒有表現出圖像放置在開始標題:(

燦有人建議我在哪裏,我可能是錯的或一些其他方法來實現我的要求

編輯:

在行:

NSCell *cell = [imageAttachment attachmentCell]; 

編譯當它被賦予這樣的警告:

type 'id <NSTextAttachmentCell>' does not conform to 'NSCopying" protocol. 

感謝,

Miraaj

+0

如果您未使用GC,請不要忘記發佈可變段落樣式,附件和屬性字符串。 – 2010-08-23 06:59:00

+0

thanx您的回覆...應用程序啓用GCC! – Devarshi 2010-08-23 07:00:22

+0

你的意思是GC嗎? GCC是GNU編譯器集合,你使用的編譯器是不相關的。 GC是垃圾收集,在這種情況下,發送Objective-C'release'消息不是嚴格必要的(但不這樣做是一種很好的方式來溫和地提醒你「如果你不使用GC,你需要釋放這些東西」在Stack Overflow上發佈代碼)。 – 2010-08-23 07:10:28

回答

1

您已經爲整個字符串的附件。你需要做的是在字符串前加上NSAttachmentCharacter,並且只爲該字符串的那部分設置附件。

您可能希望在NSAttachmentCharacter和您的實際文字之間留出空格。只有NSAttachmentCharacter應具有附件屬性。

+0

你可以建議一些代碼(作爲例子)來做到這一點? – Devarshi 2010-08-23 11:41:55

+0

http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/ – 2010-08-23 12:37:29

+0

我曾看過NSAttributedString的類引用,但在其中我不知道如何使用NSAttachmentCharacter: ( – Devarshi 2010-08-23 12:51:04