在一个看似永无止境的关于iphone开发的更多努力中,我一直在玩苹果开发者网站提供的一些源代码。我正在使用的特定示例是Core Data Books,找到here。 DetailViewController和AddViewController是以编程方式创建的,因为它们没有任何xib文件。我的问题是在不使用IB的情况下以编程方式将视图添加到视图中。我想在UITableView下面放置一个UISwitch,它包含DetailView中特定书籍的详细信息。我该怎么做呢?这是我到目前为止所尝试的:
在AddViewController中,我设置了UISwitch:
@interface AddViewController : DetailViewController {
id <AddViewControllerDelegate> delegate;
UISwitch *onoff;
}
@property (nonatomic, assign) id <AddViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UISwitch *onoff;
我还设置了IBAction:
- (IBAction)flip:(id)sender;
然后我在AddViewController.m文件中合成它,但没有任何反应。我只需要设置开关并使其成为可以控制它从我设置的IBAction中做的事情。我知道这很简单,但我无法弄清楚。所以,任何帮助将不胜感激!感谢
编辑1
所以我实现了我在viewDidLoad中指向的代码,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
UISwitch *onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
[onoff addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged];
// Set the desired frame location of onoff here
[self.view addSubview: onoff];
它抛出了两个警告,说'onoff'的本地声明隐藏了实例变量。但即使有这些收益,UISwitch弹出也好,但是当我移动或使用它时,它看起来并不完全正常。我的行动看起来像这样:
- (IBAction)flip:(id)sender {
if (onoff.on) NSLog(@"On");
else NSLog(@"Off");
}
每当开关打开时,控制台应该打开,当它关闭时,控制台应该读取。对?无论何时我移动它,它只是在控制台中重复,关闭。如果它打开,或者它关闭,它只显示。世界上我做错了什么?请帮忙!感谢
答案 0 :(得分:29)
编译器正试图帮助你。你覆盖了viewDidLoad;
中的onoff实例变量,因此永远不会被设置。在你的-flip:方法中,你引用了一个nil控制器。有两种方法可以解决这个问题:
(a)摆脱onoff的本地声明,只使用你的实例变量
(b)将sender参数转换为-flip:作为UISwitch
,并访问:
- (IBAction) flip: (id) sender {
UISwitch *onoff = (UISwitch *) sender;
NSLog(@"%@", onoff.on ? @"On" : @"Off");
}
答案 1 :(得分:16)
UISwitch
并将其添加到视图层次结构中?您的控制器的-loadView
或-viewDidLoad
实现应具有以下代码:
// Use the ivar here
onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
[onoff addTarget: self action: @selector(flip:) forControlEvents: UIControlEventValueChanged];
// Set the desired frame location of onoff here
[self.view addSubview: onoff];
[onoff release];