本文介绍了从另一个类访问 IBOutlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有两个 UIViewControllers.在第一个中,有一个包含图像的 UIButton.当用户然后到达我的第二个 ViewController 时,有许多按钮,其中包含不同的图像.因此,当用户按下我的 VC2 中的一个按钮时,它应该将图像从自身设置为我的 VC1 上的 UIButton.

Hey I have two UIViewControllers. In the first one, there's an UIButton which contains an image. When the user then gets to my second ViewController, there are many buttons, which contain different images. So, when the user presses one button in my VC2, it should set the image from itself to the UIButton on my VC1.

我已经通过添加以下内容实现了第一个 VC:#import "ViewController1.h"ViewController2.m 之前的 @interface ViewController2()

I've already implemented the first VC by adding:#import "ViewController1.h" to the ViewController2.m before @interface ViewController2 ()

我该怎么做?例如:

VC2:

- (IBAction)seaButton:(id)sender {
//Access the IBOutlet from VC1 and set the image of the Button like:

UIImage * seaBtnImage = [UIImage imageNamed:@"Sea.png"];
[buttonOutlet setImage:seaBtnImage forState:UIControlStateNormal];
}

谢谢!

推荐答案

步骤 1:在 ViewController2.h 中在 VC2 上创建一个属性以引用 VC1:

Step 1: In ViewController2.h create a property on VC2 to reference VC1:

#import "ViewController1.h"

@property (nonatomic, strong) ViewController1 *viewController1;

第2步:在VC1中创建VC2时,设置属性:

Step 2: When you create VC2 in VC1, set the property:

[viewController2 setViewController1:self];

第三步:在ViewController2上设置按钮图片

Step 3: set the button image on ViewController2

[self.buttonVC2 setImage:[self.viewController1.buttonVC1 imageForState:UIControlStateNormal] forState:UIControlStateNormal];

注意:更好的模型是在 VC1 上提供一种返回正确图像的方法.例如在 VC1 中:

Note: a better model is to provide a method on VC1 that returns the correct image. For example in VC1:

- (UIImage *)imageForButton {
    return [self.buttonVC1 imageForState:UIControlStateNormal];
}

在 VC2 中:

[self.buttonVC2 setImage[self.viewController1 imageForButton]];

这篇关于从另一个类访问 IBOutlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:02