2014-03-13 30 views
0

我有一個自定義視圖,它在屏幕上繪製一個圓。它具有顏色屬性。從ViewController類更改自定義視圖類屬性

該顏色是圓的顏色。

我有另一個ViewController是該視圖的父,並擁有另一個子視圖 - UISegmentControl。

我的願望是改變顏色屬性和視圖顏色,當我點擊一個段按鈕。 該應用程序運行時沒有錯誤,並且段操作起作用(正如我在NSLog中看到的那樣)。

那麼我在這裏錯過了什麼? (我知道我大概可以將段添加到其他視圖,但可以說,我廣東話)

這裏是我的ViewController的的loadView:

-(void)loadView 
{ 
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"red",@"blue",@"green"]]; 
//this is my costumed view: 
    BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init]; 
    self.view = backgroundView; 

    CGRect frame = self.segment.frame; 
    CGRect window = [[UIScreen mainScreen] bounds]; 
    frame.origin.x = (window.size.width-frame.size.width) /2.0; 
    frame.origin.y = window.size.height -100; 

    self.segment.frame = frame; 
    [self.segment addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged]; 
    [self.view addSubview:self.segment]; 

} 
-(void)action:(id) sender 
{ 
    NSLog(@"%@ was touched",self); 
    BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init]; 
    backgroundView.circleColor = [UIColor redColor]; 
    [backgroundView setNeedsDisplay]; 

} 

回答

1

不要重新創建一個新的觀點,只是設置在現有視圖屬性:

-(void)action:(id) sender 
{ 
    NSLog(@"%@ was touched",self); 
    BNRHypnosisView *backgroundView = (BNRHypnosisView*)self.view; 
    backgroundView.circleColor = [UIColor redColor]; 
    [backgroundView setNeedsDisplay]; 
} 

作爲一個附註,我會在視圖的setCircleColor:內調用setNeedsDisplay。這樣可以在你的BNRHypnosisView類中保留「更改圓圈顏色需要重畫視圖」的實現細節,這是更好的封裝。

+0

謝謝,多數民衆贊成在幫助。 關於封裝,如果你的意思是改變目標視圖的對象,並在那裏實現該選擇器 - 做到了這一點,並工作。 只調用setNeedsDisplay - 不能看到如何幫助雖然 – Yevgeni

1

你的觀點,但你爲什麼再分配一次。您是否已將視圖添加到視圖控制器的視圖中?如果您要添加的視圖,然後更改顏色屬性,然後像這樣做,

-(void)action:(id) sender 
{ 
    NSLog(@"%@ was touched",self); 
    BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init]; 
    backgroundView.frame = self.view.frame; 
    [self.view addSubview: backgroundView]; 
    backgroundView.circleColor = [UIColor redColor]; 

} 
相關問題