【发布时间】:2010-08-16 10:15:13
【问题描述】:
有没有人成功地在代码中创建了一个信息按钮(斜体“i”在一个圆圈中)(阅读:没有 Interface Builder),然后将其分配为导航栏的右栏按钮项?
我到处寻找,我什至找不到如何在代码中创建信息按钮。任何帮助将不胜感激。
【问题讨论】:
标签: iphone cocoa-touch ipad
有没有人成功地在代码中创建了一个信息按钮(斜体“i”在一个圆圈中)(阅读:没有 Interface Builder),然后将其分配为导航栏的右栏按钮项?
我到处寻找,我什至找不到如何在代码中创建信息按钮。任何帮助将不胜感激。
【问题讨论】:
标签: iphone cocoa-touch ipad
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
【讨论】:
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
这是一个很好看的解决方案,我认为它涵盖了人们在上面的 cmets 中提出的所有要点。类似于接受的答案,但这种方法包括额外的间距(通过修改框架),以便按钮不会撞到右边缘。
// 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!
【讨论】:
对于斯威夫特:
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];
}
【讨论】: