【问题标题】:Swift enable TableView reload while sliding through the viewSwift 在视图中滑动时启用 TableView 重新加载
【发布时间】:2018-08-02 18:40:54
【问题描述】:

在我的应用程序中,我有一个计时器,它每 0.1 秒增加一个整数 1。这个整数显示在表格视图单元格中。为了显示这个整数增加,我的表格视图控制器中有另一个计时器,它每 0.1 秒重新加载一次表格视图。这工作得很好,我遇到的唯一问题是,当我在表格视图中滑动时,价值的增加停止了;一旦我放开表格视图,就会继续增加。我很想知道一种禁用此行为的方法,以便即使用户正在滚动表格视图,表格视图也会继续重新加载。

【问题讨论】:

标签: swift tableview reload


【解决方案1】:

通过使用scheduledTimerWithTimeInterval,您的计时器被安排在默认模式的主运行循环中,防止您的计时器在您的运行循环处于非默认模式(点击或滑动)时触发。

为所有常见模式安排计时器:

@IBOutlet weak var tableView: UITableView!
var count = 0 {
    didSet {
        tableView.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (time) in
        self.count += 1
        print(self.count)
    })
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) // the magic
    tableView.delegate = self
    tableView.dataSource = self
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = String(count)
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

此代码有效。

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多