UIBarButton 不显示在代码部分之前但显示在之后

UIBarButton doesn't show before section of code but shows after

super.viewDidLoad()

let urlString: String
if navigationController?.tabBarItem.tag == 0 {
    urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
} else {
    urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"
}

if let url = URL(string: urlString) {
    if let data = try? Data(contentsOf: url) {
        parse(json: data)
        return
    }
}

navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(actionButton))

如果我在代码部分(如上)之后创建 rightBarButton,则不会显示栏按钮。但是,如果我在代码之前创建 rightBarButton,则会出现 rightBarButton。我在导航控制器和标签栏控制器中嵌入了 tableViewController。为什么在代码后制作按钮不显示按钮?

删除return关键字,return将不会执行更多的代码行。请参考 confused with the functionality of return in swift.

的回答

您的代码应该是

super.viewDidLoad()
let urlString: String = (navigationController?.tabBarItem.tag == 0) ? "https://api.whitehouse.gov/v1/petitions.json?limit=100" : "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"


if let url = URL(string: urlString) {
    if let data = try? Data(contentsOf: url) {
        parse(json: data)
    }
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(actionButton)