我正在嘗試關注如何在屏幕上繪製某些形狀的指南,但在應用程序啓動時工作正常,但我無法使用setNeedsDisplay
「重新繪製」形狀我嘗試了很多像在主線程上執行一樣的東西,但它不起作用。setNeedsDisplay not call drawRect:(CGRect)rect
我的應用程序是由這樣的:
我UIView有它自己的類,DrawView
。這裏是我的代碼:
DrawView.h
#import <UIKit/UIKit.h>
NSInteger drawType;
@interface DrawView : UIView
-(void)drawRect:(CGRect)rect;
-(void)drawNow:(NSInteger)type;
@end
DrawView.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
ViewController.h
#import <UIKit/UIKit.h>
#import "DrawView.h"
DrawView *mydraw;
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISegmentedControl *drawTypeSW;
- (IBAction)drawNow:(id)sender;
@end
ViewController.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
不叫。爲什麼?我錯過了什麼?
謝謝;)
我改變了myDraw到界面裏面,它仍然沒有工作......你是什麼意思「UIViews需要使用initWithFrame初始化」。我在DrawView.h的' - (id)initWithFrame:(CGRect)框架內需要什麼?謝謝;) – TCB13
沒有,如果你不需要任何自定義初始化。我指的是你在ViewController.m中實例化它的地方:'mydraw = [[DrawView alloc] init];'應該是更多沿'myDraw = [[DrawView alloc] initWithFrame:CGRectMake(20,100,200 ,200)];'(例如,CGRectMake的參數決定視圖的顯示位置)。鑑於你們說起初它確實畫了一條線,但我懷疑這不是問題 - 儘管它仍然是一個應該解決的問題。 – Xono
我已經做出了改變;)問題依然存在。 – TCB13