Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

iphone - Objective-c / xcode - Access button state in different class

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;
}

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");

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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

see following code

AppDelegate.h

@Property(nonatomic, ratain) ViewController *vc;

AppDelegate.m

@synthesize vc;

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...