20160913TestKitchen

掌厨

20160913TestKitchen

FoodCourseViewController

其中,下拉 刷新 ,没有用 三方库, 直接用 系统的方法。



import UIKit
import AVFoundation
import AVKit

class FoodCourseViewController: BaseViewController {
    
    //id
    var serialId: String?
    
    //表格视图
    private var tbView: UITableView?
    
    //食材课程的数据
    private var serialModel: FoodCourseModel?
    
    //当前选择的集数的序号
    private var serialIndex: Int = 0
    
    //集数的cell是合起还是展开
    private var serialIsExpand: Bool = false
    
    //评论数据的当前页数
    private var curPage = 1
    
    //评论的数据
    private var commentModel: FCComment?
    
    //评论数据是否有更多
    private var infoLabel: UILabel?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //导航
        createMyNav()
        
        //表格
        createTableView()
        
        
        //下载食课数据
        downloadFoodCourseData()
        
        //下载评论的数据
        downloadCommentData()
        
    }

    /** 下载评论的数据*/
    func downloadCommentData(){
        //methodName=CommentList&page=1&relate_id=22&size=10&token=&type=2&user_id=&version=4.32
        //methodName=CommentList&page=2&relate_id=22&size=10&token=&type=2&user_id=&version=4.32
        
        var params = Dictionary<String,String>()
        params["methodName"] = "CommentList"
        params["page"] = "\(curPage)"//
        params["size"] = "10"
        
        params["relate_id"] = serialId
        //这里
        
        
        
        
        params["type"] = "2"
        
        let downloader = KTCDownloader()
        downloader.type = .FoodCourseComment
        downloader.delegate = self
        downloader.postWithUrl(kHostUrl, params: params)
        
        
    }
    
    
    /** 下载食课数据*/
    func downloadFoodCourseData(){
        //methodName=CourseSeriesView&series_id=22&token=&user_id=&version=4.32
        
        if serialId == nil {
            return
        }
        
        //参数
        var dict = Dictionary<String,String>()
        dict["methodName"] = "CourseSeriesView"
        dict["series_id"] = serialId!
        
        let downloader = KTCDownloader()
        downloader.delegate = self
        downloader.type = .FoodCourse
        downloader.postWithUrl(kHostUrl, params: dict)
        
    }
    
    
    //导航
    func createMyNav(){
        //返回按钮
        addNavBackBtn()
    }
    
    //表格
    func createTableView() {
        
        
        automaticallyAdjustsScrollViewInsets = false
        
        tbView = UITableView(frame: CGRectMake(0, 64, kScreenWidth, kScreenHeight-64), style: .Plain)
        tbView?.delegate = self
        tbView?.dataSource = self
        
        //去掉分割线
        tbView?.separatorStyle = .None
        
        view.addSubview(tbView!)
    }
    
    /** 评论*/
    func commentAction(){
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

//MARK: KTCDownloader代理
extension FoodCourseViewController: KTCDownloaderDelegate {
    
    func downloader(downloader: KTCDownloader, didFailWithError error: NSError) {
        print(error)
    }
    
    func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) {
        
        if downloader.type == .FoodCourse {
            //食材课程数据
            /*
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(str!)
            */
            
            if let jsonData = data {
                let model = FoodCourseModel.parseModelWithData(jsonData)
                serialModel = model
                
                
                
                //回到主线程刷新UI
                dispatch_async(dispatch_get_main_queue(), {
                    [weak self] in
                    self!.tbView!.reloadData()
                    
                    //显示标题
                    let array = self!.serialModel?.data?.series_name?.componentsSeparatedByString("#")
                    if array?.count > 1 {
                        self!.addNavTitle(array![1])
                    }
                })
            }
            
            
        }
        else if downloader.type == .FoodCourseComment {
            //评论数据
            /*
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(str!)
            */
            
            if let jsonData = data {
                
                let model = FCComment.parseWithData(jsonData)
            //MARK:-   下拉刷新 在这里
                if curPage == 1 {
                    commentModel = model
                }else{
                    //加载更多
                    let mutableArray = NSMutableArray(array: (commentModel?.data?.data)!)
                    mutableArray.addObjectsFromArray((model.data?.data)!)
                    let array = NSArray(array: mutableArray)
                    commentModel?.data?.data = array as? [FCCommentDetail]
                }
                
                //刷新UI
                dispatch_async(dispatch_get_main_queue(), {
                    [weak self] in
                    
                    //判断是否有更多
                    var hasMore = false
                    if self!.commentModel?.data?.total != nil {
                        
                        let total = NSString(string: (self!.commentModel?.data?.total)!).integerValue
                        if total > self!.commentModel?.data?.data?.count {
                            hasMore = true
                        }
                    }
                    
                    //创建label
                    if self!.infoLabel == nil {
                        self!.infoLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(16), textAlignment: .Center, textColor: UIColor.blackColor())
                        self!.infoLabel?.frame = CGRectMake(0, 0, kScreenWidth, 40)
                        self!.infoLabel?.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
                        
                        self!.tbView!.tableFooterView = self!.infoLabel
                    }
                    
                    if hasMore {
                        self!.infoLabel?.text = "下拉加载更多"
                    }else {
                        self!.infoLabel?.text = "没有更多了!"
                    }
                    
                    
                    
                        self!.tbView!.reloadData()
                })
            }
        }
        
    }
    
    
    
    
}

//MARK: UITableView代理
extension FoodCourseViewController: UITableViewDelegate, UITableViewDataSource {
    
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rowNum = 0
        
        if section == 0 {
            //食材数据
            if serialModel?.data?.data?.count > 0 {
                rowNum = 3
            }
            
        }else if section == 1 {
            //评论
            if commentModel?.data?.data?.count > 0 {
                rowNum = (commentModel?.data?.data?.count)!
            }
        }
        
        return rowNum
    }
    
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        var height: CGFloat = 0
        
        if indexPath.section == 0 {
            
            if indexPath.row == 0 {
                //视频的cell
                height = 160
            }
            else if indexPath.row == 1 {
                //课程标题和描述
                if serialModel?.data?.data?.count > 0 {
                    let model = serialModel?.data?.data![serialIndex]
                    height = FCCourseCell.heightWithModel(model!)
                }
                
            }
            else if indexPath.row == 2 {
                //集数
                height = FCSerialCell.heightWithNum((serialModel?.data?.data?.count)!, isExpand: serialIsExpand)
            }
            
        }else if indexPath.section == 1 {
            
            //评论
            height = 80
        }
        
        return height
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = UITableViewCell()
        if indexPath.section == 0 {
            //获取模型对象
            let dataModel = serialModel?.data?.data![serialIndex]
            
            //食材课程的数据
            if indexPath.row == 0 {
                //视频的cell
                cell = createVideoCellForTableView(tableView, atIndexPath: indexPath, withModel: dataModel!)
                
            }
            else if indexPath.row == 1 {
                //课程名称和描述
                cell = createCoureCellForTableView(tableView, atIndexPath: indexPath, withModel: dataModel!)
            }
            else if indexPath.row == 2 {
                //集数
                cell = createSerialCellForTableView(tableView, atIndexPath: indexPath, withModel: serialModel!)
            }
            
            
        }else if indexPath.section == 1 {
            //评论
            let detailModel = commentModel?.data?.data![indexPath.row]
            cell = createCommentCellForTableView(tableView, atIndexPath: indexPath, withModel: detailModel!)
        }

        
        //取消选中状态
        cell.selectionStyle = .None
        
        return cell
    }
    
    
    /** 创建评论的cell*/
    func createCommentCellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withModel detailModel:FCCommentDetail) -> FCCommentCell {
        
        let cellId = "commentCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCCommentCell
        if nil == cell {
            cell = NSBundle.mainBundle().loadNibNamed("FCCommentCell", owner: nil, options: nil).last as? FCCommentCell
        }
        
        //数据
        cell?.model = detailModel
        
        return cell!
    }
    
    
    /** 创建视频的cell*/
    func createVideoCellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withModel model:FoodCourseSerialModel) -> FCVideoCell {
    
        let cellId = "videoCellId"
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCVideoCell
        if nil == cell {
            cell = NSBundle.mainBundle().loadNibNamed("FCVideoCell", owner: nil, options: nil).last as? FCVideoCell
        }
        
        //显示数据
        cell?.model = model
        
        cell?.videoClosure = {
            [weak self]
            urlString in
            
            let url = NSURL(string: urlString)
            let player = AVPlayer(URL: url!)
            let playerCtrl = AVPlayerViewController()
            playerCtrl.player = player
            //播放
            player.play()
            
            //显示视图控制器
            self?.presentViewController(playerCtrl, animated: true, completion: nil)
        }
        
        return cell!
        
    }
    
    /** 创建课程标题和描述文字的cell*/
    func createCoureCellForTableView(tableView: UITableView, atIndexPath indexPath:NSIndexPath,withModel model: FoodCourseSerialModel) -> FCCourseCell {
        
        let cellId = "courseCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCCourseCell
        if nil == cell {
            cell = NSBundle.mainBundle().loadNibNamed("FCCourseCell", owner: nil, options: nil).last as? FCCourseCell
        }
        
        cell?.model = model
        
        return cell!
    }
    
    /** 创建一共有多少集的cell*/
    func createSerialCellForTableView(tableView: UITableView,atIndexPath indexPath: NSIndexPath,withModel model: FoodCourseModel) -> FCSerialCell {
        
        let cellId = "serialCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FCSerialCell
        if nil == cell {
            cell = FCSerialCell(style: .Default, reuseIdentifier: cellId)
        }
        
        //代理
        cell?.delegate = self
        
        //修改展开状态
        cell?.isExpand = serialIsExpand
        //显示数据
        cell?.num = model.data?.data?.count
        //设置选中的序号
        cell?.selectIndex = serialIndex
        
        return cell!
    }
    
    
    //加载更多
    
    
    //MARK:-  Yes, 下拉 刷新 ,没有用 三方库, 直接用 系统的方法。
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let h: CGFloat = 70
        
        if scrollView.contentOffset.y > h {
            scrollView.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0)
        }else if scrollView.contentOffset.y > 0 {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
        }
        
        
        //如果没有更多了,就不加载
        if commentModel?.data?.total != nil {
            let totalCount = NSString(string:(commentModel?.data?.total)!).integerValue
            if totalCount == commentModel?.data?.data?.count {
                return
            }
        }
        
        
        let offset: CGFloat = 40
        if scrollView.contentOffset.y >= scrollView.contentSize.height-scrollView.bounds.size.height-offset {
            
            //下载下一页的数据
            curPage += 1
            downloadCommentData()
            
        }
        
        
    }
    
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 1 {
            //评论
            
            //背景视图
            let bgView = UIView.createView()
            bgView.frame = CGRectMake(0, 0, kScreenWidth, 60)
            bgView.backgroundColor = UIColor.whiteColor()
            
            //评论数
            if commentModel?.data?.total != nil {
                let str = "\((commentModel?.data?.total)!)条评论"
                let numLabel = UILabel.createLabel(str, font: UIFont.systemFontOfSize(17), textAlignment: .Left, textColor: UIColor.grayColor())
                numLabel.frame = CGRectMake(20, 4, 160, 20)
                bgView.addSubview(numLabel)
            }
            
            //评论按钮
            let btn = UIButton.createBtn("我要评论", bgImageName: nil, selectBgImageName: nil, target: self, action: #selector(commentAction))
            btn.backgroundColor = UIColor.orangeColor()
            btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            btn.layer.cornerRadius = 6
            btn.layer.masksToBounds = true
            btn.frame = CGRectMake(20, 34, kScreenWidth-20*2, 30)
            bgView.addSubview(btn)
            
            return bgView
            
            
        }
        
        return nil
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 70
        }
        return 0
    }
    
    
}

//MARK: FCSerialCell代理
extension FoodCourseViewController: FCSerialCellDelegate {
    
    func didSelectSerialAtIndex(index: Int) {
        //修改当前选择集数的序号
        serialIndex = index
        
        //刷新表格的第一个section
        
        tbView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic)
    }
    
    func changeExpandState(isExpand: Bool) {
        serialIsExpand = isExpand
        
        //刷新表格
        
        tbView?.reloadRowsAtIndexPaths([NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic)
    }
    
    
}



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容