Reputation: 4413
I'm trying to draw text in a UIView, 'erase' it, then draw it again in a different position. (Or draw different text instead)
I've got a Single Page App, Storyboard, Xcode 5, iOS 7. I've created a subclass for the UIView and can draw a single string one time using the 'drawRect' method. However, this only gets called once so it's not useful.
I've created another method in my subclass, but calling it doesn't seem to work.
How can I create a method that I can call repeatedly to draw the text?
Here's my code: MyView.h
#import <UIKit/UIKit.h>
@interface MyView : UIView
-(void)drawIt:(NSString *)inText;
@end
MyView.m
#import "MyView.h"
@implementation MyView
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// This executes once and works
-(void)drawRect:(CGRect)myRect{
UIFont *myFont=[UIFont fontWithName:@"Helvetica" size:30];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:myFont forKey:NSFontAttributeName];
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[@"TEST" drawInRect:myRect withAttributes:attributes];
}
//This is what I'd like to call repeatedly with different text or clear, etc...
//However nothing shows when I call it
-(void)drawIt:(NSString *)inText{
CGRect myRect=CGRectMake(0,0,self.bounds.size.width,self.bounds.size.height);
UIFont *myFont=[UIFont fontWithName:@"Helvetica" size:30];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentRight;
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:myFont forKey:NSFontAttributeName];
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[inText drawInRect:myRect withAttributes:attributes];
}
@end
And in my ViewController.m:
#import "TextDrawViewController.h"
#import "MyView.h"
@interface TextDrawViewController ()
@end
@implementation TextDrawViewController
- (void)viewDidLoad{
[super viewDidLoad];
MyView *xView = [[MyView alloc] init];
[xView drawIt:@"junk"];
}
@end
Upvotes: 1
Views: 2008
Reputation: 13312
It is better to place all drawing code to -(void)drawRect:(CGRect)myRect
method.
After updating text and position call [self setNeedsDisplay];
and iOS automatically will call drawRect:
method.
Upvotes: 1