2010-12-14 73 views
0

大家好! 如果有人可以幫助我,我會很高興^)如何更改本地類變量IBAction

的問題是: 我在我的類IBAction爲方法(點擊複選框),我想通過點擊複選框(進入大膽狀態改變字體屬性) 。 我試圖在IBAction方法中更改本地類變量,以便在我的 - drawRect:方法中檢查它,因爲它不工作 - 變量沒有更改。 如何更改IBAction方法中的局部變量或者有另一種方法? 謝謝。

#import <Foundation/Foundation.h> 
@interface BigLetterView : NSView { 
NSColor *bgColor; 
NSString *string; 
NSString *testString; 
BOOL isHighlighted; 
BOOL isBold; 
BOOL isItalic; 
IBOutlet NSButton *boldButton; 
NSMutableDictionary *attributes; 

} 
@property(retain, readwrite) NSColor *bgColor; 
@property(copy, readwrite) NSString *string; 
@property(readwrite) BOOL isBold; 

- (void)drawStringCenteredIn:(NSRect)r; 
- (void)prepareAttributes; 
- (void)changeIsBold; 
- (IBAction)savePDF:(id)sender; 
- (IBAction)makeBold:(id)sender; //it's that method 
- (IBAction)setItalic:(id)sender; 

這裏下面變量 'isBold' 改變爲 'YES'。 (調用方法 - 我在調試器中測試)。

- (IBAction)makeBold:(id)sender 
{ 
if ([boldButton state] == NSOnState) { 
isBold = YES; 
NSLog(@"Action bold=%d", isBold); 
} 
else { 
isBold = NO; 
NSLog(@"Action bold=%d", isBold); 
} 

} 

但是,這裏仍然是'NO'。

- (void)drawRect:(NSRect)rect { 
NSRect bounds = [self bounds]; 
[bgColor set]; 
[NSBezierPath fillRect:bounds]; 
[self drawStringCenteredIn:bounds]; 
NSLog(@"isBold: %d",isBold); //HERE prints 'isBold:0' 
if (isBold == YES) { 
NSFont *aFont = [attributes objectForKey:NSFontAttributeName]; 
NSFontManager *fontManager = [NSFontManager sharedFontManager]; 
[attributes setObject:[fontManager convertFont:aFont toHaveTrait:NSBoldFontMask] forKey:NSFontAttributeName]; 
} 

//whether this view is firstResponder 
if ([[self window] firstResponder] == self && 
[NSGraphicsContext currentContextDrawingToScreen]) { 
[NSGraphicsContext saveGraphicsState]; 
NSSetFocusRingStyle(NSFocusRingOnly); 
[NSBezierPath fillRect:bounds]; 
[NSGraphicsContext restoreGraphicsState]; 

} 
} // drawRect 

P.S.I從Aaron Hillegass的書中做第20章。

+3

請向我們展示代碼,特別是如何確保您的操作方法確實被調用。 – 2010-12-14 17:12:26

+0

感謝評論,奧萊!完成了。 – Alexander 2010-12-14 19:33:04

回答

0

你到目前爲止所展示的內容看起來不錯,但顯然它不起作用或者你不會在這裏。嘗試添加此行到您的-makeBold:方法的末尾:

[self setNeedsDisplay]; 

這將迫使視圖重新繪製自己;您的問題可能只是該視圖未被重繪。

+0

謝謝你的回答,傑夫!嘗試了一分鐘前。 - 沒有什麼變化。問題是我嘗試在IBAction中更改變量,然後在另一種方法中檢查此變量值。 (IB打印日誌)中的變量,但在另一個方法變量的舊值(看起來像IBAction中的變量,其餘的類有另一個內存空間.. – Alexander 2010-12-14 19:28:00

+0

你是如何創建視圖? – 2010-12-14 19:39:37

+0

首先,我創建了一個類,繼承自NSView,然後我在IB中拖動'Custom View',並在Class Identity中將默認的NSView拖入到以前創建的類中 – Alexander 2010-12-14 19:52:10