Objective-c/xcode - 访问不同类中的按钮状态 [英] Objective-c / xcode - Access button state in different class

查看:23
本文介绍了Objective-c/xcode - 访问不同类中的按钮状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我以多种不同的方式尝试了这个,但我无法让它工作.我试图在不同的类中更改 UIbutton 的状态.

So I tried this in many different ways but I can't get it to work. Im trying to change the state of a UIbutton in a different class.

class1.h

@property (strong, nonatomic) IBOutlet UIButton *monthly;

class2.m

- (void)viewDidLoad
{
    ViewController *vc = [[ViewController alloc] init];
    vc.monthly.enabled = NO;
}

无论我尝试什么以及将代码放在哪里,按钮状态都不会改变.当我在 class2.m 中记录状态时:

Whatever I try and where ever I put the code, the button state is not changing. When I log the state in class2.m:

NSLog(vc.monthly.enabled ? @"Yes" : @"No");

它总是返回 No,即使我只是在 class2.m 中将其声明为 YES.长话短说:我的按钮属性没有从不同的类更新.如果您需要查看更多代码,请告诉我,我会尽快更新.

It always returns No, even if I just stated it as YES in my class2.m. Long story short: My button property is not updating from a different class. Please tell me if you need to see any more code and i'll update asap.

推荐答案

我认为问题出在类实例上.以下行创建新实例

i think problem is with class instance. the following line create new instance

ViewController *vc = [[ViewController alloc] init];

ViewController *vc = [[ViewController alloc] init];

这就是为什么你的按钮状态没有改变你必须得到你之前创建的 intstace 的引用,而不需要创建新的实例.

that's why your button state is not changing you have to get reference of your previously created intstace no need to create new instance.

为此,您可以使用 AppDelegate 文件来声明 class1 的属性.

for this you can use AppDelegate file to declare property of class1.

看下面的代码

AppDelegate.h

AppDelegate.h

@Property(nonatomic, ratain) ViewController *vc;

@Property(nonatomic, ratain) ViewController *vc;

AppDelegate.m

AppDelegate.m

@synthesize vc;

@synthesize vc;

现在分配 &在需要时初始化 vc,如下所示.

now alloc & initialize vc whenever you need it like following.

AppDelegate *appDelegate = (AppDelegate *)[[UIApplicationsharedApplication] 委托];appDelegate.vc=[[ViewController alloc] init];

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.vc=[[ViewController alloc] init];

也不要忘记在您编写上述代码的地方导入 AppDelegate.h 文件.

also don't forgot to import AppDelegate.h file where you write above code.

现在使用 appDelegate.vc,您可以在项目的所有类中使用视图控制器的所有属性.

now using appDelegate.vc you can use all property of View Controller in all classes of you project.

这篇关于Objective-c/xcode - 访问不同类中的按钮状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆