I am at the 17th chapter of Aaron's Cocoa programming for Mac os X, and in the example he embeds a NSView in a NSScrollView.
For exercise I also have added a NSButton programmatically to the view.
The problem is a strange behaviour of the button, which firstly appears on the scroll view, but when I move down the vertical scroller, the button disappears and reappears in the bottom of the scroll view.Since this may be confusing (and also hard to explain), I have made a video to better describe the problem:
http://tinypic.com/player.php?v=k1sacz&s=6
I have subclassed NSView and called the class StretchView (as the book says).
This is the code:
#import <Cocoa/Cocoa.h>
@interface StretchView : NSView
{
@private
NSBezierPath* path;
}
- (NSPoint) randomPoint;
- (IBAction) click : (id) sender;
@end
#import "StretchView.h"
@implementation StretchView
- (void) awakeFromNib
{
// Here I add the button
NSView* view=self;
NSButton* button=[[NSButton alloc] initWithFrame: NSMakeRect(10, 10, 200, 100)];
[button setTitle: @"Click me"];
[button setTarget: self];
[button setAction: @selector(click:)];
[view addSubview: button];
}
- (IBAction) click:(id)sender
{
NSLog(@"Button clicked");
}
- (void) drawRect:(NSRect)dirtyRect
{
NSRect bounds=[self bounds];
[[NSColor greenColor] set];
[NSBezierPath fillRect: bounds];
[[NSColor whiteColor] set];
[path fill];
}
- (id) initWithFrame:(NSRect)frameRect
{
self=[super initWithFrame: frameRect];
if(self)
{
// here i dra some random curves to the view
NSPoint p1,p2;
srandom((unsigned int)time(NULL));
path=[NSBezierPath bezierPath];
[path setLineWidth: 3.0];
p1=[self randomPoint];
[path moveToPoint: p1];
for(int i=0; i<15; i++)
{
p1=[self randomPoint];
p2=[self randomPoint];
[path curveToPoint: [path currentPoint] controlPoint1: p1 controlPoint2: p2 ];
[path moveToPoint: p1];
}
[path closePath];
}
return self;
}
- (NSPoint) randomPoint
{
NSPoint result;
NSRect r=[self bounds];
result.x=r.origin.x+random()%(int)r.size.width;
result.y=r.origin.y+random()%(int)r.size.height;
return result;
}
@end
Questions:
1) Why does the button disappear - reappear and how to avoid this problem?
2) Why are the curves filled in white? I wanted to draw them as tiny lines, not filled.