how to replace/customize back button image in storyboard navigationcontroller

前端 未结 2 1578
执笔经年
执笔经年 2020-12-19 12:54

I want to replace the text in the back button with a custom image. How can I do that in swift code? I don\'t want to replace the entire backbarbutton since I\'d like to ke

相关标签:
2条回答
  • 2020-12-19 13:28

    Are you looking for something like this?

    btn = [UIButton buttonWithType:UIButtonTypeCustom];    
    [btn setImage:[UIImage imageNamed:@"YOURIMAGE.png"] forState:UIControlStateNormal];    
    btn.frame = CGRectMake(0, 0, 30, 30);
    [btn addTarget:self action:@selector(youraction:) forControlEvents:UIControlEventTouchUpInside];  
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:btn]autorelease];
    
    0 讨论(0)
  • 2020-12-19 13:38

    Try changing your leftBarButtonItem:

    self.navigationItem.leftBarButtonItem = 
        UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:nil);
    

    to a backBarButtonItem:

    self.navigationItem.backBarButtonItem = 
        UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:nil);
    

    in order to take advantage of backBarButtonItem's default action.

    And put that line of code in the view controller preceding the one you'd like your custom back button to appear in.

    Edit: If you don't want the "<" symbol to appear on your button, you'll have to in fact use a leftBarButtonItem then dismiss the view controller in a separate method, ex:

        self.navigationItem.leftBarButtonItem = 
            UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:"backButtonPressed:");
    
    }
    
    func backButtonPressed(sender:UIButton) {
        navigationController?.popViewControllerAnimated(true)
    }
    
    0 讨论(0)
提交回复
热议问题