简体   繁体   中英

iOS - set UIButton target and action from its super class

I have 2 classes ClassA: UIView ClassB: UIViewController

I have a UIButton in ClassA

The button is declared in the header and as an @property of A

UIButton *selectBtn;    
}
@property (nonatomic, strong) UIButton *selectBtn;

in the .m file of Class A the button is initialized and shows up on screen

ClassB imports ClassA's header file and from it I'm trying to set the target and the action for my button with the following

[ClassA.selectBtn addTarget:self action:@selector(getSomething:)     forControlEvents:UIControlEventTouchUpInside];

But i keep getting an Error message saying "Property "selectBtn" not found on object of type "ClassA"

What am I doing wrong ? any help or guidance is very appreciated

[ClassA.selectPicBtn addTarget:self action:@selector(getSomething:)     forControlEvents:UIControlEventTouchUpInside];

使用selectPIcBtn而不是selectBtn

I don't know if I'm missing something because none of the other posters brought this up but from what I see selectBtn is a property of a ClassA instance, not a property of the class itself. Try grabbing an instance of a ClassA object and then accessing the property from that instance:

//WRONG
[ClassA.selectBtn addTarget:self action:@selector(getSomething:) forControlEvents:UIControlEventTouchUpInside];

//Correct
ClassA *aClassAObject = [[ClassA alloc] init];
[aClassAObject.selectBtn addTarget:self action:@selector(getSomething:) forControlEvents:UIControlEventTouchUpInside];

Please keep in mind, the above code is just an example and is not likely the object you are looking for. If you are doing this inside the ClassB object you have to grab the ClassA UIView that is actively being used by the ClassB UIViewController. Typically, I would create a property in ClassB to access the ClassA object similar to the way you created a property for a UIButton object but I'm not sure how you have your classes setup without seeing the header files.

Problem is here.

UIButton *selectBtn;    
}
@property (nonatomic, strong) UIButton *selectPicBtn;

selectBtn and selectPicBtn are different. property name should be same as variable name. If you have declared a property then you don't need variable declaration.

Only declare property and use it. While initializing, initialize self.selectPicBtn = [UIButton.... in Class A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM