Created
November 8, 2008 03:24
-
-
Save ishikawa/23017 to your computer and use it in GitHub Desktop.
The simple custom text view (Mac OS X/Cocoa)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Cocoa/Cocoa.h> | |
@interface MyTextView : NSView { | |
NSMutableAttributedString *_text; | |
} | |
@end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "MyTextView.h" | |
@implementation MyTextView | |
- (id) initWithFrame: (NSRect) frameRect { | |
if (self = [super initWithFrame:frameRect]) { | |
_text = [[NSMutableAttributedString alloc] init]; | |
} | |
return self; | |
} | |
- (void) dealloc { | |
[_text release]; | |
[super dealloc]; | |
} | |
- (void) drawRect: (NSRect) theRect { | |
[[NSColor whiteColor] set]; | |
NSFrameRect(theRect); | |
NSRectFill(theRect); | |
[[NSColor grayColor] set]; | |
NSFrameRect(theRect); | |
[_text drawInRect: NSMakeRect( | |
theRect.origin.x + 5.0f, theRect.origin.y, | |
theRect.size.width, theRect.size.height)]; | |
} | |
// ---------------------------------------------------------------- | |
// NSResponder | |
// ---------------------------------------------------------------- | |
- (BOOL) acceptsFirstResponder { | |
return YES; | |
} | |
- (void) keyDown: (NSEvent *) theEvent { | |
[self interpretKeyEvents: [NSArray arrayWithObject: theEvent]]; | |
} | |
- (void) deleteBackward: (id) sender { | |
const NSUInteger length = [_text length]; | |
if (length > 0) { | |
[_text deleteCharactersInRange: NSMakeRange(length - 1, 1)]; | |
[self setNeedsDisplay: YES]; | |
} | |
} | |
- (void) insertNewline: (id) sender { | |
[self insertText: @"\n"]; | |
} | |
- (void) insertTab: (id) sender { | |
[self insertText: @"\t"]; | |
} | |
- (void) insertText: (id) aString { | |
[[_text mutableString] appendString: aString]; | |
[_text addAttribute: NSFontAttributeName | |
value: [NSFont userFontOfSize: 18.0f] | |
range: NSMakeRange(0, [_text length])]; | |
[self setNeedsDisplay: YES]; | |
} | |
- (void) doCommandBySelector: (SEL) aSelector { | |
[super doCommandBySelector: aSelector]; | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment