swift筆記(五)

1.下拉刷新

refreshControl = UIRefreshControl()
        
        let otherView = UIView()
        otherView.frame = CGRect(x: 0, y: 0, width: 400, height: 44)
        otherView.backgroundColor = UIColor.purpleColor()
        refreshControl?.addSubview(otherView)
        /*
        1.UIRefreshControl只要拉到一定程度無論是否松手會都觸發下拉事件
        2.觸發下拉時間之后, 菊花不會自動隱藏
        3.想讓菊花消失必須手動調用endRefreshing()
        4.只要調用beginRefreshing, 那么菊花就會自動顯示
        5.如果是通過beginRefreshing顯示菊花, 不會觸發下拉事件
        */
        refreshControl?.addTarget(self, action: Selector("loadMoreData"), forControlEvents: UIControlEvents.ValueChanged)



RefreshView.swift

import UIKit
import SnapKit

class XMGRefreshControl: UIRefreshControl {
    override init() {
        super.init()
        // 1.添加子控件
        addSubview(refreshView)
        // 2.布局子控件
        refreshView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: 150, height: 50))
            make.center.equalTo(self)
        }
        
        // 3.監聽UIRefreshControl frame改變
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit
    {
        removeObserver(self, forKeyPath: "frame")
    }
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoadingView()
    }
    
    /// 記錄是否需要旋轉
    var rotationFlag = false
    // MARK: - 內部控制方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y == 0 || frame.origin.y == -64
        {
            // 過濾掉垃圾數據
            return
        }
        
        // 判斷是否觸發下拉刷新事件
        if refreshing
        {
            // 隱藏提示視圖, 顯示加載視圖, 并且讓菊花轉動
            refreshView.startLoadingView()
            return
        }
        
        // 通過觀察發現: 往下拉Y越小, 往上推Y越大
        if frame.origin.y < -50 && !rotationFlag
        {
            rotationFlag = true
            NJLog("往上旋轉")
            refreshView.rotationArrow(rotationFlag)
        }else if frame.origin.y > -50 && rotationFlag
        {
            rotationFlag = false
            NJLog("往下旋轉")
            refreshView.rotationArrow(rotationFlag)
        }
    }
    
    // MARK: -懶加載
    private lazy var refreshView: RefreshView = RefreshView.refreshView()
}

class RefreshView: UIView {
    /// 菊花
    @IBOutlet weak var loadingImageView: UIImageView!
    /// 提示視圖
    @IBOutlet weak var tipView: UIView!
    /// 箭頭
    @IBOutlet weak var arrowImageView: UIImageView!
    
    class func refreshView() -> RefreshView {
        return NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView
    }
    
    // MARK: - 外部控制方法
    /// 旋轉箭頭
    func rotationArrow(flag: Bool)
    {
        var angle: CGFloat = flag ? -0.01 : 0.01
        angle += CGFloat(M_PI)
        /*
        transform旋轉動畫默認是按照順時針旋轉的
        但是旋轉時還有一個原則, 就近原則
        */
        UIView.animateWithDuration(2.0) { () -> Void in
            self.arrowImageView.transform = CGAffineTransformRotate(self.arrowImageView.transform, angle)
        }
    }
    
    /// 顯示加載視圖
    func startLoadingView()
    {
        // 0.隱藏提示視圖
        tipView.hidden = true
        
        if let _ = loadingImageView.layer.animationForKey("lnj")
        {
            // 如果已經添加過動畫, 就直接返回
            return
        }
        // 1.創建動畫
        let anim =  CABasicAnimation(keyPath: "transform.rotation")
        
        // 2.設置動畫屬性
        anim.toValue = 2 * M_PI
        anim.duration = 5.0
        anim.repeatCount = MAXFLOAT
        
        // 3.將動畫添加到圖層上
        loadingImageView.layer.addAnimation(anim, forKey: "lnj")
    }
    
    /// 隱藏加載視圖
    func stopLoadingView()
    {
        // 0.顯示提示視圖
        tipView.hidden = false
        
        // 1.移除動畫
        loadingImageView.layer.removeAllAnimations()
    }
}

2.顯示提醒消息

/// 顯示刷新提醒
    private func showRefreshStatus(count: Int)
    {
        // 1.設置提醒文本
        tipLabel.text = (count == 0) ? "沒有更多數據" : "刷新到\(count)條數據"
        tipLabel.hidden = false
        // 2.執行動畫
        UIView.animateWithDuration(1.0, animations: { () -> Void in
//            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, 44)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
    }

3.緩存行高

 /// 緩存行高
    private var rowHeightCaches =  [String: CGFloat]()

 // 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let viewModel = statuses![indexPath.row]
        let identifier = (viewModel.status.retweeted_status != nil) ? "forwardCell" : "homeCell"
        
        // 1.從緩存中獲取行高
        guard let height = rowHeightCaches[viewModel.status.idstr ?? "-1"] else
        {
            NJLog("計算行高")
            // 緩存中沒有行高
            // 2.計算行高
            // 2.1獲取當前行對應的cell
            let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! HomeTableViewCell
            
            // 2.1緩存行高
            let  temp = cell.calculateRowHeight(viewModel)
            
            rowHeightCaches[viewModel.status.idstr ?? "-1"] = temp
            
            // 3.返回行高
            return temp
        }
        
        // 緩存中有就直接返回緩存中的高度
        return height
    }


override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // 釋放緩存數據
        rowHeightCaches.removeAll()
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,245評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,372評論 25 708
  • 包租爺:邊伯賢(村長) 年齡:28歲 職業:寵物店店主 1號房客:樸燦烈(樸喜慶) 年齡:30歲 職業:漫畫家 2...
    柏洛yeah閱讀 435評論 0 0
  • 最好的溝通效果,是“說的人高興,聽的人開心。” 在交流過程中,想要賓主盡歡,最重要的是明確:對方想要聽到什么。 總...
    16118f1f5e2c閱讀 155評論 13 10
  • 偶遇是什么?一種緣分,一種喜悅,一種遐想。世界那么大,竟然讓我遇到了你,如此妙不可言,你在心中竊喜,思緒飛揚,該怎...
    徽音閱讀 331評論 0 0