1

我有一个 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;
}
4

3 回答 3

2

我假设因为您试图在导航控制器上执行此操作,所以您需要工具栏上的条形按钮项。您需要在 UIViewController 中执行此操作,而不是 UINavigationController:

UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                           style:UIBarButtonSystemItemDone
                                                          target:self
                                                          action:@selector(buttonPressed:)];
[self.navigationItem setRightBarButtonItem:doneButton];

此外,您应该喝杯咖啡并通读UINavigationController 类参考的“概述”部分。大约需要 10 分钟,你会很高兴你做到了。

如果我错了,并且您确实想要一个 UIButton(而不是 UIBarButtonItem),那么您还需要在 UIViewController 子类中执行此操作。此外,您应该使用它的工厂方法,而不是典型的 alloc/init:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(20, 90,28,20)
于 2013-04-25T16:12:54.210 回答
1

我不相信您可以向 a 添加按钮UINavigationController- 它实际上并没有自己的视图。更多的UINavigationController是一个幕后组织者,用于举行和展示其他UIViewControllers。

您需要将您[self.view addSubview:testbtn]的代码放入 a 的代码中UIViewController,而不是放入UINavigationViewController. 正如大卫多伊尔在他的回答中指出的那样,将类似的东西放在viewDidLoad而不是放在initWithNibName.

于 2013-04-25T15:59:50.560 回答
0

如果要修改 View Controller 的视图,在 init 方法中这样做不是一个好主意。提取创建 View Controller 视图的资源的 nib 文件需要很短的时间才能完成。

您最好通过覆盖方法 -[UIViewController viewDidLoad] 来修改 View Controller 的视图,如下所示:

- (void)viewDidLoad
{
  UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)];
  [self.view addSubview:testbtn];
}
于 2013-04-25T15:53:31.593 回答