728x90
반응형

리스트 형식의 TableView 를 사용할 때에 새로고침 버튼을 두는것보다


아래로 당기면서 새로고침을 진행하는게 좋습니다.


네이버나 페이스북 유튜브의 경우에도 제일 상단 목록을 아래로 당기면 새로운 목록이 나오게 됩니다.


iOS에서도 이러한 기능을 지원을 하고 있어서 정리합니다.





UIRefreshControl 의 내부를 보겠습니다.


@available(iOS 6.0*)
open 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.
     *
    */
    public init()
 
    
    open var isRefreshing: Bool { get }
 
    
    open var tintColor: UIColor!
 
    open var attributedTitle: NSAttributedString?
 
    
    // May be used to indicate to the refreshControl that an external event has initiated the refresh action
    @available(iOS 6.0*)
    open func beginRefreshing()
 
    // Must be explicitly called when the refreshing has completed
    @available(iOS 6.0*)
    open func endRefreshing()
}
cs


iOS 6.0 버전 이상부터 지원이 가능하고 UIControl 을 상속 받고 있습니다.


isRefreshing 은 현재 리프레쉬가 진행중인지를 나타냅니다.


tintColor 로 색상도 바꿀수 있구요.


attributedTitle 은 새로고침 indicator 아래에 텍스트를 설정합니다.


beginRefreshin 함수는 새로고침 시작을 알립니다.


endRefreshing 함수는 새로고침이 끝남을 알립니다.






이젠 실습으로 구현해 보겠습니다.



Storyboard 의 UIVIewController 에 TableView와 TableViewCell을 만들어 줍니다.


TableViewCell의 Attributes inspactor에 들어가서 indentifier 를 'Cell'로 정의해주었습니다.


Storyboard는 이정도만 만들고 Swift 코드로 넘어가겠습니다.





import UIKit
 
class ViewController: UIViewController {
    
    var array = ["Samsung""Apple""Lg""Google""Facebook"]
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        initRefresh()
    }
    
    // UIRefreshControl 초기 설정
    func initRefresh() {
        let refresh = UIRefreshControl()
        refresh.addTarget(self, action: #selector(updateUI(refresh:)), for: .valueChanged)
        refresh.attributedTitle = NSAttributedString(string: "새로고침")
 
        if #available(iOS 10.0*) {            
            tableView.refreshControl = refresh
        } else {
            tableView.addSubview(refresh)
        }
    }
    
    // 새로고침 함수
    @objc func updateUI(refresh: UIRefreshControl) {
        refresh.endRefreshing() // 리프레쉬 종료
        tableView.reloadData() // 테이블 뷰 로드
    }
}
 
cs


샘플로 만들었으며 array라는 배열에 임이의 값을 넣어주었습니다.


TableView를 IBOutlet 변수로 선언을 해주고 Storyboard의 TableView와 연결을 해주고


delegate와 dataSource를 self로 대입해 나 자신이 delegate와 dataSource 프로토콜을 준수하고 있다고 정의해줍니다.


UIRefrechControl 인스턴스화 하여 target을 설정해주면 스와이프 액션이 주어졌을때 연결한 uidateUI함수를 호출해 줍니다.




iOS 10 이전 버전은 TableView에 view를 등록해 주고, 이후는 TableView에 refreshControl 프로퍼티가 존재함으로 대입해 주면 됩니다. 


updateUI함수가 호출되면 리프레쉬를 종료하는 endRefreshing함수를 호출함으로써 새로고침 UI는 마무리가 되고


TableVIew를 재조회 합니다.





extension ViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
        cell.textLabel?.text = array[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int-> Int {
        return array.count
    }
}
cs


TableView 관련코드 입니다.


기존의 글에 많이 동일한 코드를 구현했으니 설명은 생략합니다.







TableView를 아래로 당겨줍니다.






설정했던 '새로고침'과 indicator가 나오면서 테이블을 재조회 합니다.





간단하게 TableView를 Refresh하는 방법을 알아보았습니다.


728x90
반응형

'프로그래밍 > iOS' 카테고리의 다른 글

Swift 4 UIAlertController  (0) 2019.03.05
Swift 4 TableView Section  (0) 2019.03.04
Swift 4 TableViewCell SwipeAction  (0) 2019.02.21
Swift 4 TextView PlaceHolder  (0) 2019.02.21
Swift 4 WKWebView 로딩(Indicator)  (0) 2019.02.20

+ Recent posts