2

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

4

2 回答 2

3

因为你在本地声明它。改为将其设为类的实例变量。

@interface MyClass: NSObject {
    UIImageView *imageView;
}

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

- (void)bar
{
    imageView.image = [UIImage imageNamed:@"baz"];
}
于 2013-02-01T19:24:46.060 回答
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];
于 2013-02-01T19:28:30.517 回答