Swift2.2 使用UIRefreshControl實現(xiàn)下拉刷新的簡單功能


代碼如下
<pre>
<code>
`
import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
//下拉刷新控件
let refresh = UIRefreshControl()
//表視圖
var tableView : UITableView?
//存放當(dāng)前時間的數(shù)組
var arrayDate = NSDate

//更新數(shù)據(jù)
func refreshData()
{
    //獲取當(dāng)前時間
    let newDate = NSDate()

    //在數(shù)組最前位置插入新元素
    arrayDate.insert(newDate, atIndex: 0)

    //表視圖重載數(shù)據(jù)
    tableView?.reloadData()
    
    //結(jié)束刷新
    refresh.endRefreshing()
}


override func viewDidLoad()
{
    super.viewDidLoad()
    
    arrayDate.append(NSDate())
    
    //設(shè)置表視圖的properties
    tableView = UITableView(frame: CGRectMake(0, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height-20), style: .Plain)//.Plain->標(biāo)準(zhǔn)表視圖風(fēng)格   .Grouped->分組表視圖風(fēng)格
    tableView!.rowHeight = UIScreen.mainScreen().bounds.height/10//設(shè)置cell高度
    tableView!.dataSource = self
    tableView!.delegate = self
    tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseCell")//注冊重用單元格
    
    //在view中添加子視圖tableView
    self.view.addSubview(tableView!)
    
    //設(shè)置refreshControl的properties
    refresh.backgroundColor = UIColor.blueColor()
    refresh.tintColor = UIColor.redColor()
    refresh.attributedTitle = NSAttributedString(string: "啦啦啦")
    refresh.addTarget(self, action: #selector(ViewController.refreshData), forControlEvents: .ValueChanged)
    
    //在tableView添加子視圖refresh
    tableView!.addSubview(refresh)
    
    //tableView重載數(shù)據(jù)
    tableView!.reloadData()
}


//設(shè)置表視圖節(jié)數(shù)
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

//設(shè)置表視圖中每節(jié)中的行數(shù)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return arrayDate.count
}

//設(shè)置cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    
    let cell = UITableViewCell(style: .Default, reuseIdentifier: "reuseCell")

    //設(shè)置日期格式
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy年MM月dd日/HH時mm分ss秒"
    let dateStr = dateFormatter.stringFromDate(arrayDate[indexPath.row])
    cell.textLabel?.text = dateStr
    return cell
}

}

`
</code>
</pre>


效果如下

refresh.gif

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容