Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

ios - 以编程方式设置UITableView数据源使其异步重新加载表(Setting UITableView datasource programmatically makes it reload table asynchronously)

I want to call tableView.reloadData() and be sure that after that table rows are rendered.

(我想调用tableView.reloadData()并确保在该表之后呈现行。)

The problem is that not happening when I am setting datasource programmatically before that.

(问题是,在此之前以编程方式设置数据源时不会发生。)

Example:

(例:)

class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.reloadData()
        print("after reloadData")
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("cellForRowAt")
        return UITableViewCell()
    }
}

Output is: 1. print("after reloadData") 2. print("cellForRowAt")

(输出为:1. print(“ reloadData之后”)2. print(“ cellForRowAt”))

I expect it to print “cellForRowAt” first.

(我希望它先打印“ cellForRowAt”。)

Why is that happening?

(为什么会这样呢?)

Update: It's silly but I thought reloadData() was synchronous.

(更新:这很愚蠢,但我认为reloadData()是同步的。)

What did the trick for me is: self.tableView.layoutIfNeeded() Thank you and thx this guy .

(对我来说,诀窍是:self.tableView.layoutIfNeeded()谢谢您,谢谢这个家伙 。)

  ask by RealNmae translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

函数tableView.reloadData()是异步的,它按顺序包含对dataSource方法的调用补丁,直到您首先看到打印内容为止


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...