Reputation: 987
I am trying to create a UIView in my main View Controller and add a class to it. My class simply draws a bunch of circles. Both work fine but I cant seem to add my class to the UIView. Any help/advice/suggestions is appreciated.
My UIView creator in my view controller (this works fine):
UIView *topProjectile = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[topProjectile setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:topProjectile];
And my class...(again works fine)
@implementation Planet
-(void) drawRect:(CGRect)rect{
int i;
for (i = 0; i < 60; i++){
int randomsize = arc4random() % 20;
int randomY = arc4random() % 600;
int randomX = arc4random() % 300;
float randomOpacity = (arc4random() % 50)/50.0f;
float randomR = (arc4random() % 100)/100.0f;
float randomG = (arc4random() % 100)/100.0f;
float randomB = (arc4random() % 100)/100.0f;
CGRect borderRect = CGRectMake(randomX, randomY, randomsize, randomsize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context,randomR,randomG,randomB,randomOpacity);
CGContextFillEllipseInRect (context, borderRect);
NSLog(@"hello from the planet");
}
}
@end
Upvotes: 1
Views: 99
Reputation: 2547
If Planet is a UIView subclass (as it looks like and it sounds like as you want to add an instance of it as a subview) you can add an instance of it to topProjectile as a subview as follows:
UIView *topProjectile = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[topProjectile setBackgroundColor:[UIColor whiteColor]];
Planet *myPlanet = [[Planet alloc] initWithFrame:[self defineAFrame]];//you need to set a frame for the specific planet
[topProjectile addSubview: myPlanet];
[self.view addSubview:topProjectile];
Upvotes: 0
Reputation: 6951
You need to tell the compiler that you will be using your subclass instead of UIView. Add this at the top of the .m file of your view controller if you haven't already:
#import Planet.h
Then change the "UIView
creator" in your UIViewController
to this:
//this is all fine and doesn't need to be changed
UIView *topProjectile = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[topProjectile setBackgroundColor:[UIColor whiteColor]];
int numberOfPlanetsToAdd = 10 //replace with the number of Planets you want to add
//create plannet(s) and add them to the topProjectile view
for(int i=0; i<numberOfPlan=netsToAdd; i++){
Plannet *newPlanet = [[Planet alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];//replace with any values you want
[topProjectile addSubview:Planet];
}
[self.view addSubview:topProjectile];
Upvotes: 1