leftbarbuttonitem does not show up in the navigation bar

前端 未结 7 1698
Happy的楠姐
Happy的楠姐 2021-01-17 10:07

I\'ve been developing an iOS app and have been having issues with using an image as the left bar button item in the navigation bar. I have attempted this in the following wa

相关标签:
7条回答
  • 2021-01-17 10:29

    Calling myButton.sizeToFit() before assigning to leftBarButtonItem helped me.

        let cancelButton = UIButton()
        cancelButton.backgroundColor = .red
        cancelButton.setTitle("Common/Cancel".localized, for: .normal)
        cancelButton.sizeToFit() //!!!
        let cancelBarButton = UIBarButtonItem(customView: cancelButton)
        navigationItem.leftBarButtonItem = cancelBarButton
    
    0 讨论(0)
  • 2021-01-17 10:30

    Add a Navigation Item to the Views storyboard and create an outlet for it in the ViewController. Then, use your outlet instead of self.navigationController?.navigationItem to reference leftBarButtonItem.

    0 讨论(0)
  • 2021-01-17 10:37

    I had the same problem. To see the button, I had to change the tint color, here's the code in 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()
    
    0 讨论(0)
  • 2021-01-17 10:39

    Replace your code to initialize the button as a customType like this:

    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;
    

    Hope it helps....:)

    0 讨论(0)
  • 2021-01-17 10:41

    Try to use this code,

    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; 
    
    0 讨论(0)
  • 2021-01-17 10:46

    Updated for Swift 5:

    let image = UIImage(named: "iconClose")
    let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(self.cancel))
    navigationItem.leftBarButtonItem = button
    
    0 讨论(0)
提交回复
热议问题