Objective-C: Adding UIButtons programmatically from another class
I'm having trouble connecting the dots between code and .xib files.
If I want to add a series of UIButtons programmatically to my view controller, how would I go about doing this from a separate class?
For instance, if I have MainViewController.m, which is set 开发者_StackOverflowas the root view controller in Xcode, how can I add a UIButton to that view controller from SecondViewController.m? Is this even possible?
I would essentially like to place all of my "user interface" code in a separate class.
Thanks
To do this, create a UIButton *myButton programmatically and then call [mainViewController addSubview:myButton];. This may mean you need to store a MainViewController * property in your SecondViewController class.
Important methods and properties for a UIButton instance (essentially, just take a look at the documentation, but here's a minimal set of stuff to get you started):
+[UIButton buttonWithType:buttonType]- Make sure if you're doing anything remotely custom to useUIButtonTypeCustomhere (it doesn't give you any default background images or otherwise to have tonilout)setFrame:- Position the button relative to its container and set the size, for usability reasons thewidthandheightshould be at least44pixels (as mentioned here).setTitle:forState:-UIControlStateNormalwill act as the default properties for other states too, so you may only need to set the text heresetBackgroundImage:forState:- useUIControlStateNormalandUIControlStateHighlighted/UIControlStateSelectedprimarily,UIControlStateDisabledif you wish to show it grayed out or inaccessible at any point.setImage:forState:- Use for an icon next to the button text (like an arrow pointing down for Save or up for Load, etc)setEnabled:,setHidden:,setSelected:- Transition between different button states.setHighlighted:happens automatically when you tap the button.addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside- TouchUpInside is almost always what you want for a simple button press, I'm using a method namedbuttonClicked:here to handle my button press.
Oh, and if you use [[UIButton alloc] initWith...] don't forget to [myButton release] once it's added to the mainViewController :)
use this
#import "MainViewController.h"
@interface SecondViewController
{
MainViewController *mainView;
}
@property(nonatomic, retain) MainViewController *mainView;
-(void)addButtons;
In your implementation
@synthesize mainView;
-(void)addButtons
{
UIButton *add = [UIButton alloc] init];
//do necessary stuff on button here
[self.mainView addSubview:add];
[add release];
}
In your MainViewcontroller.m
#import "SecondViewController.h"
-(void)viewDidLoad
{
[self superViewDidLoad];
SecondViewController *second = [SecondViewController alloc] init];
second.mainView = self;
[second addButton];
[second release];
}
加载中,请稍侯......
精彩评论