我有一个UINavigationController类,我想添加一个带有addSubview方法的按钮,但它不起作用
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)];
[self.view addSubview:testbtn];
}
return self;
}发布于 2013-04-25 23:59:51
我不相信你可以给UINavigationController添加一个按钮--它实际上没有自己的视图。UINavigationController更像是一个用于保存和显示其他UIViewController的幕后组织者。
您需要将[self.view addSubview:testbtn]放入UIViewController的代码中,而不是放入UINavigationViewController的代码中。正如David Doyle在他的回答中指出的那样,将类似的东西放在viewDidLoad中而不是initWithNibName中被认为是更好的做法。
发布于 2013-04-26 00:12:54
我假设,因为您正尝试在导航控制器上执行此操作,所以您希望工具栏上有一个栏按钮项。您需要在UIViewController中执行此操作,而不是在UINavigationController中:
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonSystemItemDone
target:self
action:@selector(buttonPressed:)];
[self.navigationItem setRightBarButtonItem:doneButton];此外,你应该喝杯咖啡,通读一下UINavigationController class reference的“概述”部分。这大约需要10分钟,你会很高兴你这样做了。
如果我错了,并且您确实想要一个UIButton (而不是UIBarButtonItem),那么您也需要在UIViewController子类中这样做。此外,您应该使用它的工厂方法,而不是典型的alloc/init:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(20, 90,28,20)发布于 2013-04-25 23:53:32
如果你想修改一个视图控制器的视图,在init方法中这样做不是一个好主意。提取创建View Controller视图的资源的nib文件只需要很少的时间就可以完成。
您最好通过覆盖方法-UIViewController viewDidLoad来修改视图控制器的视图,如下所示:
- (void)viewDidLoad
{
UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)];
[self.view addSubview:testbtn];
}https://stackoverflow.com/questions/16219322
复制相似问题