I would like to enter text in a NSTextView so that when I hit return the NSTextView clears with the cursor going back to the original position. Then the entered text displays on the screen using the drawRect of an NSView.
This what I have currently which doesn’t work. Basically self.outputString is always the current value of [textview string] even though I draw and then clear. The current code below doesn’t draw any string to the screen. If I remove [textview setString:@""] then the current text always shows what I’m writing.
- (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];
}
First off, set a delegate on the
NSTextobject so you can take advantage of some of the delegate methods declared by theNSTextDelegateprotocol.The method you probably want to catch first is the
textDidChange:notification, looking for when a enter is pressed.Also, does your
drawRectmethod ever get called? If you don’t know, set a breakpoint and find out. What object is thatdrawRectassociated with? Why dodrawRectanyways? You could just have a nice centeredNSTextFieldas anIBOutletand set the font on that.