UITableView 和 UIRefreshControl 因未知原因被下移

UITableView and UIRefreshControl being moved down for unknown reason

我的应用程序中有一个 UITableViewController,其中添加了 UIRefreshControl。但是有时(我不确定如何重现这个,它时不时地发生),我在 table 视图的顶部得到一些额外的空白,刷新控件甚至在其下方偏移。

长这样子(左边闲置,右边被拉下):

我不知道是什么原因造成的。在我的 viewdidload 中,我只是实例化刷新控件并调用设置属性标题的更新函数。正如我在其他地方读到的那样,我已经将刷新控件添加到 table 视图到 viewDidAppear 中。这就是代码的样子:

override func viewDidLoad() {
    super.viewDidLoad()
    self.refreshControl = UIRefreshControl()

    updateData()
}

override func viewDidAppear(animated: Bool) {
    refreshControl!.addTarget(self, action: "updateData", forControlEvents: UIControlEvents.ValueChanged)
    tableView.insertSubview(self.refreshControl!, atIndex: 0)
}

func updateData() {
    //...
    ServerController.sendParkinglotDataRequest() {
        (sections, plotList, updateError) in
        //...

        // Reload the tableView on the main thread, otherwise it will only update once the user interacts with it
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.tableView.reloadData()

            // Update the displayed "Last update: " time in the UIRefreshControl
            let formatter = NSDateFormatter()
            formatter.dateFormat = "dd.MM. HH:mm"
            let updateString = NSLocalizedString("LAST_UPDATE", comment: "Last update:")
            let title = "\(updateString) \(formatter.stringFromDate(NSDate()))"
            let attributedTitle = NSAttributedString(string: title, attributes: nil)
            self.refreshControl!.attributedTitle = attributedTitle
        })
    }
}

是否需要将刷新控件添加为 tableView 的子视图?我认为您需要做的就是分配 self.refreshControl。根据文档:

The default value of this property is nil.

Assigning a refresh control to this property adds the control to the view controller’s associated interface. You do not need to set the frame of the refresh control before associating it with the view controller. The view controller updates the control’s height and width and sets its position appropriately.

viewDidAppear 中添加子视图可能会执行多次。如果您从单元格中推送控制器并弹回,这将再次被调用。可能是 insertSubview 检查刷新是否已经有父项并首先将其删除,所以可能不是您的问题。您应该只在控制器第一次出现时才插入。

updateData 也可能被多次添加。

所以我认为您只需要分配 self.refreshControl,然后像现在使用 addTarget 一样为刷新操作添加一个处理程序,但这次是在 self.refreshControl 上执行。

您也可以从情节提要中完成所有这些操作。在情节提要中,您 select UITableViewController 和属性检查器只需将 Refreshing 属性设置为已启用。这会将 UIRefreshControl 添加到 table 中,您可以在视图层次结构中看到它。然后,您可以简单地按 CTRL 键从刷新控件正常拖动到 .h 文件中,并为 valueChange 添加一个操作,当您在 table.

中下拉刷新控件时将触发该操作

嗯,我相信您描述的行为不一定是由刷新控件引起的。 根据您的 table 视图下方没有任何其他子视图这一事实,我建议您尝试在 table 视图下方放置一个 "fake"-视图。我通常更喜欢边长为 0 的空标签。

我遇到了与您类似的问题,在某些情况下,我的 table 视图插图被破坏了。一旦我使用这个 "fake" 子视图,问题就消失了。我也在其他一些线程中读到过这个问题。解决方案是这样的。好像是个奇怪的behavior/bug.

试一试:)