Adding an IBAction button to UIViewController
I have a simple view controller with a few buttons that are defined as IBActions. I want to place them on a scroll view, basically making the whole page scrollable (let's say they are really big buttons and I have a bunch of them). How can I do that? I tried to add those buttons, but since they are defined as IBAction it did not work.
Here is some of my code. thanks!
- (IBAction) switchFromThird : (id)sender
{
//some action...
}
- (IBAction) BackHome : (id)sender
{
//some action...
}
- (void)viewDidLoad
{
[super viewDidLoad];
myScroll.contentSize = CGSizeMake(480, 1000);
myScroll.maximumZoomScale = 4开发者_运维百科.0;
myScroll.minimumZoomScale = 1.0;
myScroll.clipsToBounds = YES;
myScroll.delegate = self;
[myScroll addSubview:switchFromThird]; //???
[myScroll addSubview:BackHome]; //???
[myScroll release];
}
No, no, no.
Please read this article in iOS Developer Library. You can't add a method (function) to a view! It's like you wanted to have a computer program in your printed document on a sheet of paper!
You should do something like this:
- Write
IBOutlet UIButton *BackHomeButton
in your .h file. - Open your .xib file.
- Connect the
BackHomeButton
outlet to your button - Replace
[myScroll addSubview:BackHome];
with[myScroll addSubview:BackHomeButton];
.
Then, and only then it will work. As I said: you can print only images and text, not computer programs!
IBAction
s are not buttons. They are methods that are specially marked so that Interface Builder can find them easily. You still need to create your buttons.
You can do this in Interface Builder by dragging them from the object library onto your scrollview. You can then hook them up to your IBAction
by right-mouse-button-dragging from your new button to whichever object you are defining the IBAction
on.
If you prefer to create your buttons programmatically, you'll need to call [[UIButton alloc[ init
... and then connect the button to your method with the button's addTarget:action:forControlEvents:
method. It's not necessary to declare your methods as IBAction
s in this case, that's just something Apple put in to make it easier for Interface Builder to find relevant methods.
精彩评论