2013-02-01 46 views
2

我已經在viewDidLoad方法中以編程方式製作了此ImageView(UIImageView)。在其他方法中引用以編程方式製作的對象

UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(110, 200, 100, 100)]; 
    imageview.image = [UIImage imageNamed:@"imageviewImage.png"]; 
    [self.view addSubview:imageview]; 

但是,當我在viewDidLoad方法創建按鈕這樣我不能引用它,在同一類的其他方法。假設我想在相同類的IBAction方法中將ImageView alpha更改爲0.0f。我不能只是參考imageview的是這樣的:

-(IBAction) button { 
    imageview.alpha = 0.0f; 
    } 

什麼是與ImageView的做,如果我想引用它的另一種方法,最簡單的事情?

PS:ImageView必須以編程方式進行。

回答

2

的問題是範圍。您在viewDidLoad中創建的imageView指針只能在那裏訪問。創建一個屬性或使用標籤。

1)創建一個屬性:

// top of the .m file 
@interface MyClass() /* replace MyClass with your class name */ 
@property(strong, nonatomic) UIImageView *imageView; 
@end 

// in viewDidLoad, don't declare UIImageView *imageView, just replace 
// all mentions of it with self.imageView; 

2)或者使用標籤:

// top of the .m file 
#define kIMAGE_VIEW_TAG 128 

// in viewDidLoad 
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(110, 200, 100, 100)]; 
imageview.image = [UIImage imageNamed:@"imageviewImage.png"]; 
imageView.tag = kIMAGE_VIEW_TAG; 
[self.view addSubview:imageview]; 

// elsewhere in the code, when you want the image view 
UIImageView *imageView = (UIImageView *)[self.view viewWithTag:kIMAGE_VIEW_TAG]; 
3

因爲你在本地聲明它。把它變成你的類的一個實例變量。

@interface MyClass: NSObject { 
    UIImageView *imageView; 
} 

- (void)foo 
{ 
    imageView = [[UIImageView alloc] init]; 
} 

- (void)bar 
{ 
    imageView.image = [UIImage imageNamed:@"baz"]; 
} 
相關問題