如何在Swift中的UITableView底部显示“pull-to-refresh”元素

时间:2014-11-28 14:31:28

标签: ios uitableview swift

我需要在UIRefreshControl的底部显示UITableView,如下面的Objective-C库:

但是我使用Swift并注意到在这些库中使用"Bridging-Header.h"文件时出现了一些问题。

实现此类行为的替代方法和最简单方法是什么?

提前致谢。

2 个答案:

答案 0 :(得分:3)

我在项目中遇到了同样的问题,找到了this answer。您可以在表格底部添加UIActivityIndicatorView实例,最初隐藏,当它进入上面的if条件时,取消隐藏它并开始动画。

您可能需要更改表格的底部偏移量,添加" 1个单元格"加载时的高度,当它在if条件内完成时将其放回原位。

在Swift 3中:

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    // Use this 'canLoadFromBottom' variable only if you want to load from bottom iff content > table size
    let contentSize = scrollView.contentSize.height
    let tableSize = scrollView.frame.size.height - scrollView.contentInset.top - scrollView.contentInset.bottom
    let canLoadFromBottom = contentSize > tableSize

    // Offset
    let currentOffset = scrollView.contentOffset.y
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
    let difference = maximumOffset - currentOffset

    // Difference threshold as you like. -120.0 means pulling the cell up 120 points
    if canLoadFromBottom, difference <= -120.0 {

        // Save the current bottom inset
        let previousScrollViewBottomInset = scrollView.contentInset.bottom
        // Add 50 points to bottom inset, avoiding it from laying over the refresh control.
        scrollView.contentInset.bottom = previousScrollViewBottomInset + 50

        // loadMoreData function call
        loadMoreDataFunction(){ result in
            // Reset the bottom inset to its original value
            scrollView.contentInset.bottom = previousScrollViewBottomInset
        }
    }
}

答案 1 :(得分:0)

var refreshControl: UIRefreshControl!

//Pull to refresh
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "pullToRefresh:", forControlEvents: UIControlEvents.ValueChanged)
self.messageTableView.addSubview(refreshControl)

//Refresh the table view (pull to refresh)
func pullToRefresh(sender:AnyObject)
{
    print("pull to refresh...")
}