在故事板中创建自定义UIBarButtonItem

时间:2013-04-15 15:06:56

标签: ios storyboard uibarbuttonitem

我需要在导航栏中自定义“设置”按钮。 但是,不幸的是,我无法正确地在故事板编辑器中输入。 我只需要查看我的图片,没有按钮矩形。

enter image description here

有没有办法正确使用按钮?

感谢。

1 个答案:

答案 0 :(得分:2)

您可以在ViewController -viewDidLoad方法中添加此代码:

左侧栏按钮

UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"NavBarMapBtn.png"];
[leftButton setImage:buttonImage forState:UIControlStateNormal];
leftButton.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[leftButton addTarget:self action:@selector(changeView) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];

或右侧栏按钮:

UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"NavBarMapBtn.png"];
[rightButton setImage:buttonImage forState:UIControlStateNormal];
rightButton.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[rightButton addTarget:self action:@selector(changeView) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

无需在xib或storyboard中为视图添加BarButtonItem。

这就是它的样子:

enter image description here