我需要在导航栏中自定义“设置”按钮。 但是,不幸的是,我无法正确地在故事板编辑器中输入。 我只需要查看我的图片,没有按钮矩形。
有没有办法正确使用按钮?
感谢。
答案 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。
这就是它的样子: