简体   繁体   English

如何在 Swift 中以编程方式创建“返回”UIBarButton 项?

[英]How to programmatically create a "Back" UIBarButton item in Swift?

I was able to create a UIBarButton item that can go back programmatically using the following code:我能够创建一个 UIBarButton 项目,该项目可以使用以下代码以编程方式返回:

    func backAction() -> Void {        
        self.navigationController?.popViewControllerAnimated(true)
    }
override func viewDidLoad() {
        super.viewDidLoad()
    let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "backAction")

        self.navigationItem.leftBarButtonItem = backButton
    }

The problem is that the back button doesn't have the left pointing arrow:问题是后退按钮没有向左箭头: 在此处输入图片说明 Is there a way to make it look like a regular back button with the arrow like this:有没有办法让它看起来像一个带有箭头的常规后退按钮,如下所示: 在此处输入图片说明

I would also like to know if there is a way to make the button title names as the title of the previous view controller, if that's possible.如果可能的话,我还想知道是否有办法将按钮标题名称设为前一个视图控制器的标题。

Thanks谢谢

Below is the code by using UIButton with image you can add it as a customView for UIBarButtonItem下面是使用带有图像的 UIButton 的代码,您可以将其添加为 UIBarButtonItem 的自定义视图

override func viewDidLoad() {
    super.viewDidLoad()
    var backbutton = UIButton(type: .Custom)
    backbutton.setImage(UIImage(named: "BackButton.png"), forState: .Normal) // Image can be downloaded from here below link 
    backbutton.setTitle("Back", forState: .Normal)
    backbutton.setTitleColor(backbutton.tintColor, forState: .Normal) // You can change the TitleColor
    backbutton.addTarget(self, action: "backAction", forControlEvents: .TouchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
}

func backAction() -> Void {        
   self.navigationController?.popViewControllerAnimated(true)
}

返回按钮.png Download Link下载链接

For setting the title of backbutton with the previous view controller title you have to pass the Title as a String while presenting the controller make change to above code as要使用前一个视图控制器标题设置后退按钮的标题,您必须在呈现控制器时将标题作为字符串传递,将上面的代码更改为

var titleStrFromPreviousController: String // This value has to be set from previous controller while presenting modal controller
backbutton.setTitle(titleStrFromPreviousController, forState: .Normal)

This may help.这可能会有所帮助。

Swift 3斯威夫特 3

override func viewDidLoad() {
    super.viewDidLoad()

    addBackButton()
}

func addBackButton() {
    let backButton = UIButton(type: .custom)
    backButton.setImage(UIImage(named: "BackButton.png"), for: .normal) // Image can be downloaded from here below link
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor
    backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

@IBAction func backAction(_ sender: UIButton) {
   let _ = self.navigationController?.popViewController(animated: true)
}

Updated for Swift 4.2 - thanks to sam bing and silentbeep为 Swift 4.2 更新- 感谢 sam bing 和 silentbeep

Made some modifications on some colors and action's selector.对一些颜色和动作的选择器进行了一些修改。

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue
        self.navigationItem.title = title
        self.navigationController?.navigationBar.barTintColor = .white
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: makeBackButton())
    }

    func makeBackButton() -> UIButton {
        let backButtonImage = UIImage(named: "backbutton")?.withRenderingMode(.alwaysTemplate)
        let backButton = UIButton(type: .custom)
        backButton.setImage(backButtonImage, for: .normal)
        backButton.tintColor = .blue
        backButton.setTitle("  Back", for: .normal)
        backButton.setTitleColor(.blue, for: .normal)
        backButton.addTarget(self, action: #selector(self.backButtonPressed), for: .touchUpInside)
        return backButton
    }

    @objc func backButtonPressed() {
        dismiss(animated: true, completion: nil)
//        navigationController?.popViewController(animated: true)
    }

You can do by embedding your view in a navigation controller.您可以通过将视图嵌入到导航控制器中来实现。 Here is an image showing how to do that:这是一张图片,展示了如何做到这一点: 导航控制器

Hope it helps :D希望它有帮助:D

For future searches, I wanted to add that you can now use the default icon by this code:对于未来的搜索,我想补充一点,您现在可以通过以下代码使用默认图标:

override public func viewDidLoad() {
    // create chevron image
    let config = UIImage.SymbolConfiguration(pointSize: 25.0, weight: .medium, scale: .medium)
    let image = UIImage(systemName: "chevron.left", withConfiguration: config)

    // create back button
    let backButton = UIButton(type: .custom)
    backButton.addTarget(self, action: #selector(self.close(_:)), for: .touchUpInside)
    backButton.setImage(image, for: .normal)
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

@IBAction func close(_ sender: UIButton) {
    self.navigationController?.dismiss(animated: true, completion: nil)
}

The first answer works great however the image is a bit too big so use the preview and scale it down to width:13 and height: 22, also set its rendering mode to .alwaysTemplate and change the UIButton 's tint to white, while also adding two spaces before the string : " Back".第一个答案效果很好但是图像有点太大所以使用预览并将其缩小到宽度:13 和高度:22,还将其渲染模式设置为.alwaysTemplate并将UIButton的色调更改为白色,同时也在字符串前添加两个空格:“Back”。 This will result in something that is quiet similar to the navigation bar back button, the image could be better in terms of size and placement.这将导致类似于导航栏后退按钮的安静,图像在大小和位置方面可能会更好。

Edited code:编辑的代码:

     func addBackButton() {


            let backButtonImage = UIImage(named: "BackButton.png")?.withRenderingMode(.alwaysTemplate)

            let backButton = UIButton(type: .custom)
            backButton.setImage(backButtonImage, for: .normal) 
            backButton.tintColor = .white
            backButton.setTitle("  Back", for: .normal)
            backButton.setTitleColor(.white, for: .normal)
            backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)


}

I changed one last line of code from selected answer and it works for me.我从选定的答案中更改了最后一行代码,它对我有用。

override func viewDidLoad() {
    super.viewDidLoad()

    addBackButton()
}

func addBackButton() {
    let backButton = UIButton(type: .custom)
    backButton.setImage(UIImage(named: "BackButton.png"), for: .normal) // Image can be downloaded from here below link
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor
    backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

@IBAction func backAction(_ sender: UIButton) {
   let _ = self.dismiss(animated: true, completion: nil)
}

Swift 5斯威夫特 5

override func viewDidLoad() {
            super.viewDidLoad()
            let backbutton = UIButton(type: .custom)
            backbutton.setImage(UIImage(named: "BackButton.png"), for: .normal) // Image can be downloaded from here below link
            backbutton.setTitle("Back", for: .normal)
            backbutton.setTitleColor(backbutton.tintColor, for: .normal) // You can change the TitleColor
            backbutton.addTarget(self, action: Selector(("backAction")), for: .touchUpInside)
    
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
        }
    
        func backAction() -> Void {
            self.navigationController?.popViewController(animated: true)
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM