Search code examples
ioscore-graphicsdrawrect

drawRect being called but the code within it not being executed when run?


I had chosen the single view application template from XCODE 4.5.2. I have an appdelegate , a viewcontroller with a RDViewController.xib which I had made a type of my UIView class Graphics. Also I have Graphics.h and Graphics.m (drawRect Method in it). There is a graphics property in viewController.m of type Graphics class. When run the drawRect method being called but nothing drawn on the simulator. The initWithFrame method in Graphics class not being called. The RDViewController.xib is made subclass of Graphics.

in appdelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[RDViewController alloc] initWithNibName:@"RDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

in only one ViewController i have written:

@implementation RDViewController

@synthesize graphics;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.graphics setNeedsDisplay];
}

in the UIView subclass Graphics

@implementation GraphicsView

- (id)initWithFrame:(CGRect)frame
{
    NSLog(@"Frame: %@", NSStringFromCGRect(frame));
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *helveticaBold;

    [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];

    NSString *myString = @"Test string function";

    [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                withFont:helveticaBold];

    self.backgroundColor = [UIColor whiteColor];
}

When run the drawRect method being called but nothing drawn on the simulator. The initWithFrame method in Graphics class not being called. The RDViewController.xib is made subclass of Graphics.


Solution

  • You never set the font. Do this:

    - (void)drawRect:(CGRect)rect
    {
        // Drawing code
        UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];
    
        NSString *myString = @"Test string function";
    
        [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                    withFont:helveticaBold];
    }
    

    And the background color should be set in the initWithFrame: method.