I'm trying to make my main ViewController with a custom view draw multiple custom UIView's to the main view, but somehow they are not drawing, I'm trying to draw dots.
My code is:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MyCustomView *myView = (MyCustomView *)self.view;
myView.xAxisLabel1 = @"customlabels 1";
myView.xAxisLabel2 = @"customlabels 2";
myView.xAxisLabel3 = @"customlabels 3";
myView.xAxisLabel4 = @"customlabels 4";
CustomDotView *newDot = [[CustomDotView alloc] initWithPointAtXCord:10 andYCord:10 withRadius:10 andColor:[UIColor redColor]];
[self.view addSubview:newDot];
}
But this is not working, I wonder if the constructor of my CustomDotView is correct or I'm doing something incorrectly
This is my CustomDotView constructor
-(id)initWithPointAtXCord:(float)xCord andYCord:(float)yCord withRadius:(float)radius andColor:(UIColor *)color {
self = [super init];
self.color = color;
self.xCordenate = xCord;
self.yCordenate = yCord;
self.radius = radius;
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetFillColorWithColor(context, color.CGColor);
CGRect currentRect = CGRectMake(xCordenate, yCordenate, radius * 2 , radius * 2);
NSLog(@"draw point?");
CGContextAddEllipseInRect(context, currentRect);
CGContextDrawPath(context, kCGPathFillStroke);
}
Any suggestions?
Ok, I went ahead and wrote this out in Xcode and it works great. Here's the simplest use case I could come up with; this is inside a blank UIViewController
.
@implementation ViewController
- (void)viewDidLoad
{
CustomDotView *newDot = [[CustomDotView alloc] initWithPointAtXCord:10 andYCord:10 withRadius:10 andColor:[UIColor redColor]];
[self.view addSubview:newDot];
}
@end
@implementation CustomDotView
-(id)initWithPointAtXCord:(float)inputXCoord andYCord:(float)inputYCoord withRadius:(float)inputRadius andColor:(UIColor *)inputColor
{
xCoord = inputXCoord;
yCoord = inputYCoord;
color = inputColor;
radius = inputRadius;
self = [super initWithFrame: CGRectMake(xCoord, yCoord, radius * 2, radius * 2)];
self.backgroundColor = [UIColor clearColor];
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextAddEllipseInRect(context, rect);
CGContextDrawPath(context, kCGPathFill);
}
@end
If you want to move the Dot around, just simply change it's frame.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.