I'm just getting started with Objective-C programming and I'm a little bit confused about where to declare a UISegmentedController
instance as a "subview" of my viewController
root view.
I've been experimenting with the code and it seems to work regardless of whether its created in "loadView", viewDidLoad
, or initWithNibName: bundle:
and I'm wondering why this is so, and also where the correct place to create it would be.
All the views in the hierarchy were created programmatically.
Code:
UISegmentedControl
code that I'm unsure where to place:
self.segCon = [[UISegmentedControl alloc]
initWithItems:(NSArray *)@[@"Red",@"Green", @"Blue"]];
self.segCon.frame = CGRectMake(35, 200, 250, 50);
[self.segCon addTarget:self
action:@selector(changeColor:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segCon];
BNRHypnosisViewController.m
:
#import "BNRHypnosisViewController.h"
#import "BNRHypnosisView.h"
@interface BNRHypnosisViewController()
@property (strong, nonatomic) UISegmentedControl *segCon;
- (void)changeColor:(id)sender;
@end
@implementation BNRHypnosisViewController
-(void)loadView
{
//create a view
BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc] init];
//set it as *the* view of this view controller
self.view = backgroundView;
Do I place the UISegmentedControl
code here?
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
//Set the tab bar items title
self.tabBarItem.title = @"Hypnotize";
//Create a UIImage from the file
// This will use Hypno@2x.png on retina devices
UIImage *i = [UIImage imageNamed:@"Hypno.png"];
//put the image on the tab bar
self.tabBarItem.image = i;
or here?
}
return self;
}
-(void)viewDidLoad
{
//Always call the super implementation of viewdidload
[super viewDidLoad];
NSLog(@"BNRHypnosisViewController loaded its view");
or here?
}
- (void)changeColor:(id)sender
{
NSLog(@"The Segment controller was touched %d", self.segCon.selectedSegmentIndex);
if(self.segCon.selectedSegmentIndex == 0){
((BNRHypnosisView *)self.view).circleColor = [UIColor redColor];
}
if(self.segCon.selectedSegmentIndex == 1){
((BNRHypnosisView *)self.view).circleColor = [UIColor greenColor];
}
if(self.segCon.selectedSegmentIndex == 2){
((BNRHypnosisView *)self.view).circleColor = [UIColor blueColor];
}
}
@end
Any help would be greatly appreciated, thank you in advance for your feedback!
I normally put such code in viewDidLoad
. But since you have a need to implement loadView
, you can setup the segmented control there.
Don't do it in the init...
method because then you end up needlessly loading the view from the init...
method.