iOS 使用UIRefreshControl来刷新UITableView等控件

释放双眼,带上耳机,听听看~!

iOS开发中, 经常需要添加UITableView的下拉刷新功能, 使用UIRefreshControl就可以非常方便得实现.

UIRefreshControl

下边是UIRefreshControl的头文件.

import Foundation
import UIKit
//
//  UIRefreshControl.h
//  UIKit
//
//  Copyright 2012-2014 Apple Inc. All rights reserved.
//
@availability(iOS, introduced=6.0)
class UIRefreshControl : UIControl {
/* The designated initializer
* This initializes a UIRefreshControl with a default height and width.
* Once assigned to a UITableViewController, the frame of the control is managed automatically.
* When a user has pulled-to-refresh, the UIRefreshControl fires its UIControlEventValueChanged event.
*/
init()
var refreshing: Bool { get }
var tintColor: UIColor!
var attributedTitle: NSAttributedString?
// May be used to indicate to the refreshControl that an external event has initiated the refresh action
@availability(iOS, introduced=6.0)
func beginRefreshing()
// Must be explicitly called when the refreshing has completed
@availability(iOS, introduced=6.0)
func endRefreshing()
}

可见, 其提供的调用方法很简单, init()是创建该控件必须的, 接下来就是 beginRefreshing() 和endRefreshing()这两个控制刷新的方法了.

使用实例

以UITableView的刷新为例, UIRefreshControl的使用分为以下几个步骤:
1. 初始化一个UIRefreshControl对象.
2. 添加刷新时调用的方法, 这里是refreshDataSource()方法.
3. 将UIRefreshControl对象添加到tableView中.
然后, 下拉设备屏幕即可看到效果.

    var refreshCtl = UIRefreshControl()
var httpCtl: HttpController = HttpController()
// outlets
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
httpCtl.delegate = self
refreshCtl.attributedTitle = NSAttributedString(string: "下拉刷新")
refreshCtl.addTarget(self, action: "refreshDataSource", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshCtl)
refreshDataSource()
}
func refreshDataSource() {
refreshCtl.beginRefreshing()
httpCtl.getDataViaNSURLConnection("http://0.0.0.0/dataapi")
refreshCtl.endRefreshing()
}

人已赞赏
iOS文章

iOS 强大的网络通信类库AFNetworking

2021-1-15 3:01:27

iOS文章

iOS 分别使用NSTimer及setKeepAliveTimeout来实现定时任务

2021-1-15 4:16:27

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索