我一直在开发iOS应用程序,并且在使用图像作为导航栏中的左栏按钮项目时遇到了问题。我通过以下方式尝试过此方法:
UIImage *backButtonImage = [UIImage imageNamed:@"backbuttonCB"];
CGRect buttonFrame = CGRectMake(0, 0, backButtonImage.size.width, backButtonImage.size.height);
UIButton *backButton = [[UIButton alloc] initWithFrame:buttonFrame];
[backButton setImage:backButtonImage forState:UIControlStateNormal];
UIBarButtonItem *backBarButtonItem= [[UIBarButtonItem alloc] initWithCustomView: backButton];
self.navigationItem.leftBarButtonItem = backBarButtonItem;
运行应用程序时,似乎从不显示条形按钮。
然后我继续尝试以下其他方法。
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backbuttonCB"] style:UIBarButtonItemStylePlain target:nil action:@selector(methodname)];
这种方法确实有效。但是,显示的图像是蓝色的,看起来不像它的意思。更改此图像的色调颜色没有帮助。
知道如何解决这个问题吗?
编辑:更多信息,如果它有帮助。这是导航堆栈中的第一个视图。导航堆栈以模态方式显示,即存在先前的视图控制器,并且在先前的视图控制器和导航控制器之间存在模态segue。这是导航堆栈中的第一个视图。
编辑:问题是固定的。我认为这是xcode中的一个错误,因为当我重新启动xcode并使用实际设备而不是模拟器进行测试时,它运行正常。但是,仍然似乎无法在模拟器上工作。
尝试以这种方式设置leftBarButtonItem。虽然以模态方式呈现但它没有显示出来。
self.navigationController?.navigationBar.topItem.leftBarButtonItem =
在分配给myButton.sizeToFit()
之前打电话给leftBarButtonItem
帮助了我。
let cancelButton = UIButton()
cancelButton.backgroundColor = .red
cancelButton.setTitle("Common/Cancel".localized, for: .normal)
cancelButton.sizeToFit() //!!!
let cancelBarButton = UIBarButtonItem(customView: cancelButton)
navigationItem.leftBarButtonItem = cancelBarButton
尝试使用此代码,
self.navigationItem.hidesBackButton=YES;
UIImage *buttonImage = [UIImage imageNamed:@"Back"];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:buttonImage forState:UIControlStateNormal];
aButton.frame = CGRectMake(0.0,0.0,buttonImage.size.width,buttonImage.size.height);
[aButton addTarget:self action:@selector(backBtnTapped) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:aButton];
self.navigationItem.leftBarButtonItem = backButton;
我有同样的问题。要查看按钮,我必须更改色调颜色,这是Swift中的代码:
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image:UIImage.init(named: "btn_back_default")!, style:UIBarButtonItemStyle.Plain, target: self, action: Selector("back"))
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
替换您的代码以将按钮初始化为customType
,如下所示:
UIImage *backButtonImage = [UIImage imageNamed:@"backButtonCB"];
CGRect buttonFrame = CGRectMake(0, 0, backButtonImage.size.width, backButtonImage.size.height);
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setFrame:buttonFrame];
[backButton setImage:backButtonImage forState:UIControlStateNormal];
UIBarButtonItem *backBarButtonItem= [[UIBarButtonItem alloc] initWithCustomView: backButton];
self.navigationItem.leftBarButtonItem = backBarButtonItem;
希望能帮助到你....:)
将导航项添加到Views故事板并在ViewController中为其创建插座。然后,使用您的outlet而不是self.navigationController?.navigationItem
来引用leftBarButtonItem。