如何在 xcode 中以编程方式向导航栏添加按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25783303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a button to a navigation bar programmatically in xcode
提问by Mowi
I'm trying to add button to navigation bar i want to add the button without any action any help please?
我正在尝试向导航栏添加按钮,我想在没有任何操作的情况下添加按钮,请问有什么帮助吗?
回答by Fahim Parkar
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
}
回答by Greg
You should add UIBarButtonItem to Nav bar instead of UIButton. T do that you can call this:
您应该将 UIBarButtonItem 添加到导航栏而不是 UIButton。这样做你可以称之为:
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithTitle:@"Title"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
self.navigationItem.rightBarButtonItem = button;
回答by Itachi Uchiha
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
}
回答by MaappeaL
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;