【发布时间】:2014-04-17 15:31:07
【问题描述】:
我正在尝试在 UIView 中绘制文本,“擦除”它,然后在不同的位置再次绘制它。 (或者改为绘制不同的文本)
我有一个单页应用程序、Storyboard、Xcode 5、iOS 7。 我为 UIView 创建了一个子类,并且可以使用“drawRect”方法一次绘制一个字符串。 但是,这只会被调用一次,所以它没有用。
我在我的子类中创建了另一个方法,但调用它似乎不起作用。
如何创建一个可以重复调用来绘制文本的方法?
这是我的代码: 我的视图.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
【问题讨论】:
标签: ios objective-c drawrect