我刚刚开始使用 Objective-C 编程,我对在哪里将实例声明为我的根视图UISegmentedController
的“子视图”有点困惑。viewController
我一直在试验代码,无论它是否在“loadView”中创建,它似乎都可以工作viewDidLoad
,或者initWithNibName: bundle:
我想知道为什么会这样,以及创建它的正确位置在哪里。
层次结构中的所有视图都是以编程方式创建的。
代码:
UISegmentedControl
我不确定放在哪里的代码:
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;
我把UISegmentedControl
代码放在这里吗?
}
-(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;
还是这里?
}
return self;
}
-(void)viewDidLoad
{
//Always call the super implementation of viewdidload
[super viewDidLoad];
NSLog(@"BNRHypnosisViewController loaded its view");
还是这里?
}
- (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
任何帮助将不胜感激,提前感谢您的反馈!