2012-01-19 35 views
0

我想在NSTextView中輸入文本,以便當我點擊返回時NSTextView清除,光標回到原始位置。然後輸入的文字使用NSViewdrawRect顯示在屏幕上。從NSTextView獲取字符串,然後返回光標開始

這是我目前沒有工作。基本上self.outputString始終是當前值[textview string]儘管我畫了然後清除。下面的當前代碼不會在屏幕上繪製任何字符串。如果我刪除[textview setString:@""]那麼當前文本總是顯示我正在寫什麼。

- (void)drawRect:(NSRect)dirtyRect 
{ 
    [[NSColor whiteColor] setFill]; 

    NSRectFill(dirtyRect); 

    // Drawing code here. 

    NSPoint point = NSMakePoint(50.0f, 700.0f); 
    NSMutableDictionary *font_attributes = [[NSMutableDictionary alloc] init]; 
    NSFont *font = [NSFont fontWithName:@"Futura-MediumItalic" size:35.0f]; 
    [font_attributes setObject:font forKey:NSFontAttributeName]; 
    [self.outputString drawAtPoint:point withAttributes:font_attributes]; 
    [font_attributes release]; 
} 


- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector { 

    [self enterPressed:[textView string]]; 
    [textView setString:@""]; 


    NSRange range = { 0, 0 }; 
    [self.textView setSelectedRange: range]; 

    return YES; 
} 

- (void) enterPressed:(NSString*)stringEntered 
{ 
    NSLog(@"enter pressed with string: %@", stringEntered); 

    self.outputString = stringEntered; 
    [self setNeedsDisplay:YES]; 
} 

回答

2

首先,設置NSText對象的委託,所以你可以充分利用一些由NSTextDelegate protocol聲明的委託方法的優勢。

您可能首先想要捕捉的方法是textDidChange: notification,您可以查找何時按下回車鍵。

此外,您的drawRect方法有沒有被調用?如果你不知道,請設置一個斷點並找出答案。什麼對象是drawRect與?反正爲什麼要做drawRect?你可以有一個很好的居中的NSTextField作爲IBOutlet並設置字體。

+0

是的,drawRect肯定會被調用。你指的是什麼NSText對象?這是一個NSTextView。你能澄清嗎? –

+0

['NSTextView'繼承自'NSText'](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextView_Class/Reference/Reference.html),所以如果你設置了一個委託,無論你指定的委託都會得到'textDidChange:'通知。 –

+0

我已經玩過這個,它似乎檢測到我改變文本時,但不是當我打回來。我想知道是否應該使用NSTextField。你肯定有幫助,但不幸的是我仍然有點失落。 –

相關問題