Reputation: 262
in my ViewController I have a button:
- (IBAction)drawLineClick:(id)sender
{
CGRect rect;
rect.origin.x = 20.0f;
rect.origin.y = 40.0f;
rect.size.width = 100.0f;
rect.size.height = 100.0f;
//draw line
DrawLine *drawLine = [[DrawLine alloc] initWithFrame:rect];
[self.view addSubview:drawLine];
}
in my DrawLine class I just draw a line:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[super setBackgroundColor:[UIColor clearColor]];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
[self drawLine];
}
- (void)drawLine
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetLineWidth(context, 3.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 50, 50);
CGContextStrokePath(context);
}
This works great but this is not variable. Every time it's the same line. How can I pass the line color, line width, etc. from the ViewController to the DrawLine class, so that I can draw different lines?
Thanks.
Upvotes: 2
Views: 2068
Reputation: 3504
Here is the code worked for me, I passed lineWidth parameter:
DrawLine.h file
#import <Cocoa/Cocoa.h>
@interface DrawLine : NSView
@property (nonatomic, strong) double *lineWidth;
@property (nonatomic, strong) UIColor *color;
- (void)drawRect:(CGRect)rect;
- (id)initWithFrame:(NSRect)frameRect andLineWidth :(double)lineWidth0 andColor: (UIColor *) color0;
...
@end
DrawLine.m file
...
- (id)initWithFrame:(NSRect)frameRect andLineWidth :(double)lineWidth0 andColor: (UIColor *) color0;
{
self.lineWidth = lineWidth0;
self = [super initWithFrame:frameRect];
if (self) {
// Initialization code
[super setBackgroundColor:color0];
}
return self;
return self;
}
...
ViewController.m file
...
- (IBAction)drawLineClick:(id)sender
{
CGRect rect;
rect.origin.x = 20.0f;
rect.origin.y = 40.0f;
rect.size.width = 100.0f;
rect.size.height = 100.0f;
double lineWidth = 10;
UIColor *color = [UIColor clearColor];
//draw line
DrawLine *drawLine = [[DrawLine alloc] initWithFrame:rect andLineWidth: lineWidth andColor: color];
[self.view addSubview:drawLine];
}
...
It works.
Upvotes: 0
Reputation: 31016
Create properties in your DrawLine class that represent the things you want to control. When you create the new object, set its properties either by assigning them directly or passing them in a custom initWith...
method. Use the property values in drawRect:.
Upvotes: 1