iPhone:在代码中的导航栏中将“添加信息”按钮添加为右侧栏按钮项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iPhone:在代码中的导航栏中将“添加信息”按钮添加为右侧栏按钮项相关的知识,希望对你有一定的参考价值。
有没有人在代码中创建一个信息按钮(斜体'我'在一个圆圈中)成功(读取:没有Interface Builder),然后将其指定为导航栏的右侧栏按钮项?
我到处寻找,我甚至无法找到如何在代码中创建信息按钮。任何帮助将不胜感激。
答案
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
另一答案
这是一个非常好看的解决方案,我认为涵盖了人们在上述评论中提出的所有要点。与接受的答案类似,但这种方法包括额外的间距(通过修改框架),以便按钮不会被撞到右边缘。
// 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!
另一答案
对于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
}
另一答案
我想这将是更完整的响应,它应该在任何情况下有所帮助:
-(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];
}
以上是关于iPhone:在代码中的导航栏中将“添加信息”按钮添加为右侧栏按钮项的主要内容,如果未能解决你的问题,请参考以下文章