Objective-c / xcode – 访问不同类中的button状态
所以我尝试了很多不同的方式,但是我无法实现。 我试图改变一个不同的类的UIbutton的状态。
class1.h
@property (strong, nonatomic) IBOutlet UIButton *monthly;
class2.m
- (void)viewDidLoad { ViewController *vc = [[ViewController alloc] init]; vc.monthly.enabled = NO; }
无论我尝试什么以及在哪里放置代码,button状态都不会改变。 当我在class2.m中logging状态时:
NSLog(vc.monthly.enabled ? @"Yes" : @"No");
它总是返回否,即使我刚才在class2.m中表示为YES
。 长话短说:我的button属性不是从一个不同的类更新。 请告诉我,如果你需要看到更多的代码,我会尽快更新。
我认为问题是与类实例。 以下行创build新的实例
ViewController * vc = [[ViewController alloc] init];
这就是为什么你的button状态不变,你必须得到你以前创build的intstace的引用,不需要创build新的实例。
为此,您可以使用AppDelegate文件声明class1的属性。
看下面的代码
AppDelegate.h
@Property(nonatomic,ratain)ViewController * vc;
AppDelegate.m
@synthesize vc;
现在alloc和初始化vc,只要你需要它像下面。
AppDelegate * appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.vc = [[ViewController alloc] init];
也不要忘记导入AppDelegate.h文件,你在上面写的代码。
现在使用appDelegate.vc,您可以在您的项目的所有类中使用View Controller的所有属性。
主要的问题是每次你要检查button的状态时你正在创build新的实例。 但button状态是您在class1.h
创build的button。 所以你需要在Appdelegate
类中创buildbutton,并在你正在检查button状态的类中从Appdelegate
中获取实例,并检查button的状态。 我认为这会有所帮助。
使用已经在堆栈中的ViewController
类的对象访问该button。 不需要创build一个新的对象,如ViewController *vc = [[ViewController alloc] init];
。 当你这样做时,它创build一个新的对象,所以你没有得到写的东西。
- 以编程方式更改iOS键盘宽度的方法?
- iOS使用什么函数/系统调用来读取和写入文件
- 如何从应用程序内监视networking活动?
- 构建Swift框架的挑战(C ++,Objective C和Swift)
- 在Google Analytics iOS SDK v3中设置用户性别和年龄
- 如何在Swift中分配CoreData多对多的关系?
- 为什么在访问titleLabel属性时UIButton会resize?
- 现有UIImage上的GPUImage Harrisangular点检测提供了黑屏输出
- 当我添加一个UIContainerView到视图控制器它的types是UIView。 如何到达embedded视图的视图控制器?