我正在尝试遵循有关如何在屏幕上绘制一些形状的指南,但在应用程序启动时它工作正常,但我无法使用“重新绘制”形状setNeedsDisplay
我已经尝试了很多漂浮的东西,比如执行主线程,但它不起作用。
我的应用程序是由这个组成的:
我的 UIView 有它自己的类,DrawView
. 这是我的代码:
绘图视图.h
#import <UIKit/UIKit.h>
NSInteger drawType;
@interface DrawView : UIView
-(void)drawRect:(CGRect)rect;
-(void)drawNow:(NSInteger)type;
@end
绘图视图.m
#import "DrawView.h"
@implementation DrawView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *color = [UIColor orangeColor];
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetFillColorWithColor(context, color.CGColor);
NSLog(@"Type: %i",drawType);
switch (drawType) {
case 0:
CGContextMoveToPoint(context, 10, 100);
CGContextAddLineToPoint(context, 300, 300);
CGContextSetLineWidth(context, 2.0);
CGContextStrokePath(context);
break;
case 1:
CGContextAddEllipseInRect(context,CGRectMake(10, 100, 300,440));
CGContextDrawPath(context, kCGPathFillStroke);
break;
case 2:
CGContextAddRect(context, CGRectMake(10, 100,300,300));
CGContextDrawPath(context, kCGPathFillStroke);
break;
default:
break;
}
}
-(void)drawNow:(NSInteger)type {
drawType = type;
NSLog(@"Draw Now! %i",drawType);
//[self setNeedsDisplay]; // Not working...
//[self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; // Not Working
}
@end
视图控制器.h
#import <UIKit/UIKit.h>
#import "DrawView.h"
DrawView *mydraw;
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISegmentedControl *drawTypeSW;
- (IBAction)drawNow:(id)sender;
@end
视图控制器.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize drawTypeSW;
- (void)viewDidLoad
{
[super viewDidLoad];
mydraw = [[DrawView alloc] init];
}
- (void)viewDidUnload
{
[self setDrawTypeSW:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)drawNow:(id)sender {
[mydraw drawNow:drawTypeSW.selectedSegmentIndex];
}
@end
当我打开应用程序时,会画一条线,但是当我尝试使用按钮绘制其他内容时,Draw Now
它不起作用,什么也没有发生,- (void)drawRect:(CGRect)rect
也没有被调用。为什么?我错过了什么?
谢谢 ;)