我试图在UIView中绘制文字,'擦除'它,然后在不同的位置再次绘制它。 (或者改为绘制不同的文字)
我有单页应用,故事板,Xcode 5,iOS 7。 我已经为UIView创建了一个子类,并且可以使用' drawRect'来绘制一个单独的字符串。方法。 但是,这只会被调用一次,因此无用。
我已经在我的子类中创建了另一个方法,但是调用它似乎不起作用。
如何创建一个可以反复调用以绘制文本的方法?
这是我的代码: 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
在我的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
答案 0 :(得分:1)
最好将所有绘图代码放到-(void)drawRect:(CGRect)myRect
方法中
更新文字和位置调用[self setNeedsDisplay];
后,iOS会自动调用drawRect:
方法。