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

Dav*_*ter 15 iphone cocoa-touch ipad

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

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

小智 33

UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
Run Code Online (Sandbox Code Playgroud)

  • 没关系,想通了:`[infoButton addTarget:self action:@selector(showInfo)forControlEvents:UIControlEventTouchUpInside];` (4认同)

Kyl*_*egg 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!
Run Code Online (Sandbox Code Playgroud)