开发者

iPhone: Adding Info button as right bar button item in navigation bar in code

Has anyone had any success creating an info button (italic 'i' in a开发者_JAVA百科 circle) in code (read: without Interface Builder), and then assigning it as the right bar button item of a navigation bar?

I've looked everywhere, and I can't even find how to create an info button in code. Any help would be greatly appreciated.


UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];


Here's a pretty good looking solution that I think covers all the points people brought up in the comments above. Similar to the accepted answer, but this approach includes extra spacing (via modifying the frame) so that the button isn't smashed up against the right edge.

// Create the info button
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];

// Adjust the frame by adding an addition 10 points to its width so the button is padded nicely
infoButton.frame = CGRectMake(infoButton.frame.origin.x, infoButton.frame.origin.y, infoButton.frame.size.width + 10.0, infoButton.frame.size.height);

// Hook the button up to an action
[infoButton addTarget:self action:@selector(showInfoScreen) forControlEvents:UIControlEventTouchUpInside];

// Add the button to the nav bar
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

// Also make sure to add a showInfoScreen method to your class!


For Swift:

func addRightNavigationBarInfoButton() {
    let button = UIButton(type: .infoDark)
    button.addTarget(self, action: #selector(self.showInfoScreen), for: .touchUpInside)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

@objc func showInfoScreen() {
    // info bar button pressed
}


I guess it will be more complete response and it should help in any situation:

-(void)viewDidLoad{

    //Set Navigation Bar
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];

    //Set title if needed
    UINavigationItem * navTitle = [[UINavigationItem alloc] init];
    navTitle.title = @"Title";

    //Here you create info button and customize it
    UIButton * tempButton = [UIButton buttonWithType:UIButtonTypeInfoLight];

    //Add selector to info button
    [tempButton addTarget:self action:@selector(infoButtonClicked) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem * infoButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];

    //In this case your button will be on the right side
    navTitle.rightBarButtonItem = infoButton;

    //Add NavigationBar on main view
    navBar.items = @[navTitle];
    [self.view addSubview:navBar];

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜