Swift: Reload a View Controller

2019-03-23 02:29发布

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?

5条回答
放荡不羁爱自由
2楼-- · 2019-03-23 02:59

In Swift 4:

self.view.layoutIfNeeded()
查看更多
\"骚年 ilove
3楼-- · 2019-03-23 03:02

Whatever code you are writing in viewDidLoad, try to add that in viewWillappear(). I think this will solve your problem.

查看更多
等我变得足够好
4楼-- · 2019-03-23 03:10

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()

查看更多
Viruses.
5楼-- · 2019-03-23 03:21

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

查看更多
The star\"
6楼-- · 2019-03-23 03:24

At any point call when you want to reload viewController's View or any view

<View you want to reload>.setNeedsLayout()
<View you want to reload>.layoutIfNeeded()
查看更多
登录 后发表回答