简体   繁体   English

如何在Xcode中以编程方式向导航栏添加按钮

[英]How can I add a button to a navigation bar programmatically in xcode

我正在尝试将按钮添加到导航栏中,我想不做任何操作就添加按钮,请问有什么帮助吗?

UIBarButtonItem *yourButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Your Button"                                         
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(methodName:)];
self.navigationItem.rightBarButtonItem = yourButton;
[yourButton release];

And then method 然后方法

-(IBAction)methodName {
    // your code here
}

You should add UIBarButtonItem to Nav bar instead of UIButton. 您应该将UIBarButtonItem而不是UIButton添加到导航栏。 T do that you can call this: 为此,您可以这样称呼:

UIBarButtonItem *button = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Title"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:nil
                               action:nil];
self.navigationItem.rightBarButtonItem = button;
UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
     [self.navigationItem setRightBarButtonItem:customBtn];

///// called event /////称为事件

-(IBAction)customBtnPressed:(id)sender
{
    //Your code here
}

if UIButton is you really want, try this. 如果确实需要UIButton,请尝试此操作。

    UIButton *btnSample = [[UIButton alloc] initWithFrame:btnFrame];
    btnSample.backgroundColor = [UIColor blueColor];

    UIBarButtonItem *barBtn_cart = [[UIBarButtonItem alloc] initWithCustomView:btnSample];

   self.navigationItem.rightBarButtonItem = btnSample;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式将按钮项添加到现有导航栏 Xcode - How to add button item to existing navigation bar programmatically Xcode 如何通过单击按钮以编程方式添加导航栏 - How to add Navigation bar programmatically by clicking the button 如何以编程方式将导航栏添加到presentModalViewController? - How can i add a navigation bar to presentModalViewController programmatically? iOS:如何在按下按钮时以编程方式在导航栏上添加搜索栏? - iOS: how to add a search bar on navigation bar programmatically on a button press? 如何在Swift Xcode 8.2中以编程方式将导航控制器嵌入到选项卡栏控制器中? - How can I embed my navigation controller into my tab bar controller programmatically in Swift Xcode 8.2? 如何使用Xcode在导航栏中添加分享按钮的操作 - How to add an action to share button in navigation bar with Xcode 如何以编程方式在导航栏下方添加视图? - How do I programmatically add a view right under the navigation bar? 如何将按钮添加到导航栏 - How to add button to navigation bar Swift / XCode 6.4:向导航栏中的导航控制器添加后退按钮 - Swift/XCode 6.4: add back button to navigation controller in navigation bar iPad:如何在不更换后退按钮的情况下向导航栏添加标签? - iPad: How can I add a label to the navigation bar without replacing the back button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM