Reputation: 987
I am a noob with obj C, and I feel like I am doing everything right so please don't hate me for this ;)...I am trying to make a custom class that draws a rectangle onto a view controller.
So far I have made a class called 'Planet' with the drawrect code. I then added the Planet class (custom class tab) to a view controller on the storyboard. I get no errors but I also get no rectangle.
Planet.h
#import <UIKit/UIKit.h>
@interface Planet : UIViewController
@end
Planet.m
#import "Planet.h"
@implementation Planet
-(void) drawRect:(CGRect)rect{
CGRect rectangle = CGRectMake(0, 100, 320, 100);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextFillRect(context, rectangle);
}
@end
And a screen of my view controller calling the Planet class.
Outputs...
Upvotes: 0
Views: 823
Reputation: 5824
Instead of Planet being a subclass of UIViewController
, make it a subclass of UIView
. The add an instance of Planet to the view of the view controller, maybe in the viewWillAppear
method, e.g.:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
Planet *myPlanet = [[Planet alloc] initWithFrame:self.view.frame];
[self.view addSubview:myPlanet];
}
Upvotes: 0
Reputation: 51
use
[self.view setNeedsDisplay];
in view will appear added subview as planet(UIView).
Upvotes: 0
Reputation: 25459
To fix this issue just change the class in storyboard from Planet to what it was previously. Drag a UIView to the view controller and change class for that view to Planet.
You should avoid override of drawRect: if you don't need it because it's very expensive. Instead you should use Layer. You can do something like that to draw rectangle with CALayer:
// Remember to import QuartzCore.h framework
#import <QuartzCore/QuartzCore.h>
CALayer *myLayer = [CALayer layer];
myRect = CGRectMake(0.0f, 0.0f, 150.0f, 200.0f);
[myLayer setBounds:myRect];
[myLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[myLayer setBorderColor:[[UIColor clearColor] CGColor]];
[myLayer setBorderWidth:1.0f];
//You can change radius
[myLayer setCornerRadius:15.0];
[self.layer addSublayer:myLayer];
It's much less expensive than drawRect:.
Upvotes: 0
Reputation: 4792
UIView
has drawRect
method.Not UIViewController
.
UIViewController
and UIView
both are subclasses of UIResponder
. And UIViewController
is not a subclass of UIView
.
And UIView
alone has drawRect method.so if you write drawRect in UIViewController, it just thinks its user defined function and won't call it.
If you still have doubt, put a breakpoint in that drawRect function and see whether it is called or not.
Upvotes: 3