Swift: Reload a View Controller

限于喜欢 提交于 2019-12-21 03:10:45

问题


I need to refresh a view controller when a certain button is tapped. Simply activating viewDidLoad() does not seem to be working for what I need to do. However, when I leave the view controller then come back to it, it seems to work perfectly?

How can I refresh/reload a view controller as if I have left it then come back to it without ever actually leaving it?


回答1:


Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.




回答2:


You shouldn't call viewDidLoad method manually, Instead if you want to reload any data or any UI, you can use this:

override func viewDidLoad() {
    super.viewDidLoad();

    let myButton = UIButton()

    // When user touch myButton, we're going to call loadData method
    myButton.addTarget(self, action: #selector(self.loadData), forControlEvents: .TouchUpInside)

    // Load the data
    self.loadData();
}

func loadData() {
    // code to load data from network, and refresh the interface
    tableView.reloadData()
}

Whenever you want to reload the data and refresh the interface, you can call self.loadData()




回答3:


This might be a little late, but did you try calling loadView()?




回答4:


In Swift 4:

self.view.layoutIfNeeded()



回答5:


If you are using a navigation controller you can segue again to the current UIViewController and it will be refreshed.



来源:https://stackoverflow.com/questions/31207783/swift-reload-a-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!