2013-04-25 42 views
1

我有一个UINavigationController类,我想在一个按钮添加与方法addSubview但它不工作的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; 
} 
+0

你怎么称呼这个类?你确定这种方法被解雇吗?在调用这个类之前,你确定调用了'alloc initWithNibName:'吗? – 2013-04-25 15:54:06

+0

更重要的是,你试图实现什么功能?这个按钮在哪里,它的功能是什么?对我而言,这将决定代码的存在位置和/或允许我们建议更好的方法来实现您要实现的功能。 – vinnybad 2013-04-25 15:56:51

回答

2

我不相信你可以添加一个按钮到UINavigationController - 它不”实际上有自己的看法。 UINavigationController更像是一个幕后组织者,用于持有和展示其他UIViewController

您需要带上您的[self.view addSubview:testbtn],并将其放入UIViewController的代码中,而不是代码中的UINavigationViewController。正如David Doyle在他的回答中指出的那样,在viewDidLoad而不是initWithNibName中放置类似的东西被认为是更好的做法。

0

如果你想修改视图控制器的看法,它不是一个好主意,做所以在init方法中。提取创建视图控制器视图的资源的nib文件需要一小段时间才能完成。

你最好不要修改视图控制器的视图通过重写方法 - [UIViewController的viewDidLoad中]像这样:

- (void)viewDidLoad 
{ 
    UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)]; 
    [self.view addSubview:testbtn]; 
} 
+0

什么也没有改变,即使在viewDidLoad,我的班级是 @ DetailImagesViewController接口UINavigationController 我觉得addSubview不工作 – 2013-04-25 16:02:26

1

我认为,因为您正在尝试在导航控制器上执行此操作,所以您需要工具栏上的酒吧按钮项。你需要做这在的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)