【发布时间】:2014-05-18 16:13:19
【问题描述】:
我刚刚开始使用 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
任何帮助将不胜感激,提前感谢您的反馈!
【问题讨论】:
-
旁注 - 如果您以编程方式做所有事情(我自己做),那么您为什么要实现
initWithNibName:bundle:方法?只需执行init。 -
这是个好问题。我实际上正在关注“iOS 编程 - Big Nerd Ranch 指南”一书,这就是它的指示。在我创建这个视图控制器的 appDelegate 中,我使用了 init。我认为因为 initwithNibName... 是指定的初始化程序,所以无论如何都会调用它,并且 nibName 和 bundle 的参数都是 nil 。话虽这么说,我想我可能只是重写了 init 而不是隐式调用 initWithNibName ...
-
是的,因为你没有使用笔尖,只需覆盖
init。它更简单、更干净。 -
我使用了本书的前一版本,这让我使用了界面构建器(.xib 文件)来创建一些视图控制器。
-
@SantaClaus 是的,3 个 viewController 中有 2 个使用界面构建器。但是我发布的那个没有。也许它是为了一致性而写的..?
标签: ios objective-c uisegmentedcontrol viewdidload loadview