问题
Hi I am new to iOS programming and am wondering what is the difference between dragging a UIView into the storyboard and create them programmatically.
I am using an iPad for development. I have a UISplitView. Inside the Appdelegate.m, I created a UISplitViewController programmatically:
MyTableViewController* orders = [[MyTableViewController alloc] initWithClassName:@"Order"];
MyDetailsViewController* details = [[MyDetailsViewController alloc] init];
UISplitViewController* splitViewController = [[UISplitViewController alloc] init];
splitViewController.viewControllers = [NSArray arrayWithObjects: orders, details, nil];
self.window.rootViewController = splitViewController;
[self.window makeKeyAndVisible];
Inside the storyboard, I have the root view controller's class set to MyTableViewController and the detail view controller's class to MyDetailsViewController. However, if I drag another UILabel into the storyboard of MyDetailsViewController and wire it as a property of the class. It does not show up. I can only create it programmatically inside viewDidLoad().
- (void)viewDidLoad
{
[super viewDidLoad];
//self.testLabel was dragged into the storyboard and added as a property of the class
[self.testLabel setText:@"TESTING!"];
[self.view addSubview:self.testLabel];
// creating programmatically
UILabel *program = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
program.text = @"im a string";
program.hidden = NO;
[self.view addSubview:program];
// The second one program shows up
}
Why is this the case here?
回答1:
Whenever you do a drag & drop in the story board, it actually creates a XML based file that holds every detail about the component. So there is no (objective -C) code generated. You can right click the storyboard & open it as source code to see the XML file. Any design in story board can be viewed even before the program is compiled or running.
When you write the code, your view / view controller can be viewed only by compiling & then running the build in simulator.
Kindly right click storyboard & open it as source code, you can see how it is represented in XML tags.
I hope that helps.
回答2:
You can write an IBOutlet in .h file of your MyDetailsViewController
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
Then go to storyboard and right click on your UILabel. You can see New Referencing Outlet there. Drag it to your view controller. There you will get myLabel in options. Select it. Then you can access that UILabel in your Storyboard in coding. Thus you can reduce the code and also customise UILabel properties in XIB itself avoiding coding.
来源:https://stackoverflow.com/questions/21421811/difference-between-dragging-uiviews-into-storyboard-and-creating-them-programmat