我已经通过UIImageView方法以编程方式制作了此ImageView(viewDidLoad)。

  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必须以编程方式制作。

最佳答案

问题是范围。您只能在此处访问在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];

09-10 09:33
查看更多