将图像设置为后退按钮

时间:2014-11-30 18:38:31

标签: ios swift uinavigationcontroller uinavigationbar

我正在尝试将BackButton设置为图像而不是标准文本和backArrow,但无论我做什么都不会工作。我试图隐藏BackButton并设置leftBarbutton,但后面的backButton不是hidng,我尝试设置backBarButtonItem如下,但仍然只出现标准的backButton。我做错了什么?

    var backButton:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "left"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("goBack:"))

    self.navigationController?.navigationItem.backBarButtonItem = backButton

现在尝试

    var backButton:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "left"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("goBack:"))

    self.navigationController?.navigationItem.leftBarButtonItem = backButton

2 个答案:

答案 0 :(得分:1)

  1. 获取UIButton并设置其图像,帧并添加目标。

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *backButtonImage = [UIImage imageNamed:@"MyImage"];
    [backButton setImage:backButtonImage forState:UIControlStateNormal];
    [backButton setImage:backButtonImage forState:UIControlStateHighlighted];
    backButton.frame = CGRectMake(0, 0, 40, 40);
    [backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
  2. 使用此backButton定义UIBarButtonItem并将其指定给 self.navigationItem.leftBarButtonItem

    UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    

答案 1 :(得分:0)

您不应该直接使用self.navigationController?.navigationItem,而是self.navigationItem

但无论如何,更多背景:

  

当此导航项位于堆栈顶部项目的正下方时,导航控制器将从此导航项目中导出导航栏的后退按钮。

(来自backBarButtonItem的Apples文档 )

这意味着,backBarButton item属性只能更改您推送到UINavigationController堆栈的下一个viewController的后退按钮外观。

要达到预期效果,您可以

  1. 设置leftBarButtonItem(这应该会自动隐藏后退按钮)并在点击时手动调用self.navigationController.popViewControllerAnimated(true)
    1. 使用UINavigationBar.appearance() API。