以编程方式添加导航栏

时间:2014-02-23 13:53:38

标签: ios

我试图以编程方式将导航栏添加到应用程序,但我没有取得任何成功。

我曾尝试过下面提到的代码

UIBarButtonItem *alefttbarButton = [[UIBarButtonItem alloc] initWithTitle:@"Setting"   style:UIBarButtonItemStyleBordered target:self action:@selector(settingAction:)];

alefttbarButton.style = UIBarButtonItemStyleBordered;
alefttbarButton.tintColor= [UIColor redColor];

self.navigationItem.leftBarButtonItem=alefttbarButton;
self.navigationController.delegate=self;
self.title =@"test";

1 个答案:

答案 0 :(得分:0)

我是这样做的。在这个特殊情况下,我手动创建了我的观点。从applicationDidFinishLaunching开始,我有以下代码:

UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mainCtl = [[MainController alloc] init];
[window addSubview:mainCtl.nav.view];
[window makeKeyAndVisible];

正如您所看到的,我在这里分配并初始化MainController的实例,它是UIViewController的子类。 然后,在这个MainController的初始化中,我调用了导航栏的初始化代码:

[self initNavBar];

这是以下功能:

- (void) initNavBar
{
    printf("initNavBar entered\n");
    self.nav = [[UINavigationController alloc] initWithRootViewController: self];

    //setup the middle view
    int btnCount = 4;
    CGRect buttonsFrame = CGRectMake(0, 0, btnCount*BUTTONWIDTH + (btnCount-1)*BUTTONSPACING + 2*BUTTONMARGIN, BUTTONHEIGHT + 2*BUTTONMARGIN);
    UIView *buttonsView = [[UIView alloc] initWithFrame:buttonsFrame];
    UIButton *button;
    CGFloat left = BUTTONMARGIN;

    // create button for photo selector invocation
    button = [self buttonWithName:@"photo" target:self selector:@selector(showImagePicker) left:left];
    //button = [self createButton:@"photo" action:@selector(showImagePicker) left:left];
    [buttonsView addSubview:button];

    left += (BUTTONWIDTH+BUTTONSPACING);
    button = [self buttonWithName:@"crop" target:self selector:@selector(cropImage) left:left];
    [buttonsView addSubview: button];

    left += (BUTTONWIDTH+BUTTONSPACING);
    kissButton = [self buttonWithName:@"kiss" target:self selector:@selector(cropImage) left:left];
    [buttonsView addSubview: kissButton];

    //left += (BUTTONWIDTH+BUTTONSPACING);
    left += (BUTTONWIDTH+BUTTONSPACING);
    button = [self buttonWithName:@"mail" target:self selector:@selector(showMailDialog) left:left];
    //button = [self createButton:@"mail" action:@selector(showMailDialog) left:left];
    [buttonsView addSubview:button];
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    //only enable the mail button if the class exists
    button.enabled = (mailClass != nil);

    printf("initNavBar done\n");
}

这是所有正常工作的代码。如果你能看透这些残骸,你就能设法得到照片。 希望这会有所帮助。