2014-04-15 4 views
0

최근 뷰를 그리기 위해 코어 그래픽을 배우기 시작했지만 setNeedsDisplay을 호출 할 때마다 메서드가 실행되지만 drawRect을 트리거하지 않습니다. 내 프로젝트에서는 뷰 컨트롤러에 대한 뷰가 있습니다. 뷰에는 BOOL 변수가 YES 또는 NO인지 확인하는 drawRect의 if 문이 있습니다. YES이면 코드를 사용하여 빨간색 원을 그립니다. 아니오이면 파란색 원을 그립니다. BOOL의 설정자는 setNeedsDisplay을 호출합니다. ViewController에서이 뷰 클래스의 인스턴스를 만들고 BOOL을 설정했지만 뷰가 다시 그려지지 않습니다. 그 방법이 왜 불리지 않는가? 아래 xcode 파일과 코드 비트를 게시했습니다.drawRect가 setNeedsDisplay에서 호출되지 않음

Customview.m :

#import "CustomView.h" 

@implementation CustomView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     [self setup]; 
    } 
    return self; 
} 

-(void)awakeFromNib{ 
    [self setup]; 
} 

-(void)setup{ 
    _choice1 = YES; 
} 

-(void)setChoice1:(BOOL)choice1{ 
    _choice1 = choice1; 
    [self setNeedsDisplay]; 
} 


// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect 
{ 
    if (_choice1) { 
     UIBezierPath * redCircle = [UIBezierPath bezierPathWithOvalInRect:rect]; 
     [[UIColor redColor]setFill]; 
     [redCircle fill]; 
    }else if (!_choice1){ 
     UIBezierPath * blueCircle = [UIBezierPath bezierPathWithOvalInRect:rect]; 
     [[UIColor blueColor]setFill]; 
     [blueCircle fill]; 

    } 
} 

@end 

CustomView.h :

#import <UIKit/UIKit.h> 

@interface CustomView : UIView 

@property (nonatomic) BOOL choice1; 

@end 

ViewController.m :

#import "ViewController.h" 
#import "CustomView.h" 

@interface ViewController() 
- (IBAction)Change:(id)sender; 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)Change:(id)sender { 
    CustomView * cv = [[CustomView alloc]init]; 
    [cv setChoice1:NO]; 
} 
@end 

전체 프로젝트 : https://www.mediafire.com/?2c8e5uay00wci0c

감사

답변

1

ViewControllerCustomView의 콘센트를 만들어야합니다. 새 CustomView 인스턴스를 만드는 코드를 삭제하고 _cv을 사용하여 customView를 참조하십시오.

@interface ViewController() 
- (IBAction)Change:(id)sender; 

@property (weak,nonatomic) IBOutlet CustomView *cv; 

@end 

그런 다음 스토리 보드에서 ViewController의 cv 출력을 CustomView에 연결합니다. 또한 CustomViewinitFromCoder: 메소드를 구현해야합니다.

- (id)initWithCoder:(NSCoder *)aDecoder { 
    if ((self = [super initWithCoder:aDecoder])) { 
     [self setup]; 
    } 
    return self; 
} 
+0

스토리 보드에보기를 추가하고 맞춤 클래스를 설정했습니다. 어떻게 그 클래스의 인스턴스에서 메소드를 호출 할 수 있습니까? – user2950916

+0

'Change :'메소드에서 새로운 인스턴스를 생성하므로 스토리 보드 인스턴스에 첨부되지 않습니다. 대신 스토리 보드 인스턴스를 View Controller에 연결해야합니다. 내 대답을 업데이트 할게. – ThomasW

+0

완벽한! 그것은 효과가있다! 고마워요. 유감스럽게도 충분한 점수가 없기 때문에 투표를 할 수 없습니다. – user2950916