Reputation: 9731
I'm trying to append a string to the view with the drawAtPoint:point withAttributes:attrs
method, but the string is not to be seen anywhere inside the view, or at least I cannot see it (it might be that the color is the same as the view, white).
The following code is what I use in the viewDidLoad
of my view controller:
NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];
[stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];
NSString *someString = [NSString stringWithFormat:@"%@", @"S"];
[someString drawAtPoint:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2) withAttributes: stringAttributes];
What is it that I'm doing wrong ?
EDIT: After following @rokjarc's suggestions, I have created a view controller with a drawRect
method that adds the string to the current context:
#import <Foundation/Foundation.h>
@interface XYZSomeView : UIView
@end
#import "XYZSomeView.h"
#import "NSString+NSStringAdditions.h"
@implementation XYZSomeView
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];
[stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];
NSString *someString = [NSString stringWithFormat:@"%@", @"S"];
[someString drawAtPoint:CGPointMake(rect.origin.x, rect.origin.y) withAttributes: stringAttributes];
NSLog(@"%@", someString);
CGContextRestoreGState(context);
}
@end
And inside my root view controller I init the XYZSomeView
:
#import "XYZRootViewController.h"
#import "XYZSomeView.h"
@implementation XYZRootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
XYZSomeView *someView = [[XYZSomeView alloc] init];
[self.view addSubview:someView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
NSLog(@"%@", @"XYZRootViewController reveived memory warning");
}
@end
The issue is that my drawRect
is not called, is that because I have to call it myself ? I thought that this method should be called upon initialization without me having to call it.
Upvotes: 2
Views: 1429
Reputation: 18875
You will need a reference to current graphics context in order to use this function: docs. You don't have this reference within viewDidLoad:
. Usually this is done within drawRect:
. There are ways to use it while generating a content off screen - but this doesn't seem to fit your needs.
If you want to add a simple text to a view controller in its' viewDidLoad
consider adding simple UILabel
with transparent background to the view of this view controller.
Upvotes: 2