iPhone:在代码中的导航栏中将“添加信息”按钮添加为右侧栏按钮项

问题描述 投票:15回答:4

有没有人在代码中创建一个信息按钮(斜体'我'在一个圆圈中)成功(读取:没有Interface Builder),然后将其指定为导航栏的右侧栏按钮项?

我到处寻找,我甚至无法找到如何在代码中创建信息按钮。任何帮助将不胜感激。

iphone cocoa-touch ipad
4个回答
33
投票
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

6
投票

这是一个非常好看的解决方案,我认为涵盖了人们在上述评论中提出的所有要点。与接受的答案类似,但这种方法包括额外的间距(通过修改框架),以便按钮不会被撞到右边缘。

// 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!

1
投票

对于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
}

0
投票

我想这将是更完整的响应,它应该在任何情况下有所帮助:

-(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];

}
© www.soinside.com 2019 - 2024. All rights reserved.