8.11 TableView

实现cell显示不同的内容

import UIKit
import SwiftyJSON
import Kingfisher

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var newsJson: JSON?

    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()

        createViews()

    }

    func createViews() {

        let tableView = UITableView(frame: self.view.bounds, style: .Plain)

        self.view.addSubview(tableView)

        

        tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier:"cell1")

        tableView.registerClass(SecondTableViewCell.self, forCellReuseIdentifier:"cell2")

        tableView.registerClass(ThirdTableViewCell.self, forCellReuseIdentifier:"cell3")

        

        tableView.dataSource = self

        tableView.delegate = self

    }

    

    func loadData() {

        let path = NSBundle.mainBundle().pathForResource("data", ofType: "json")

        let data = NSData(contentsOfFile: path!)

        newsJson = JSON(data: data!)

//        

//        if newsJson![0]["images"] == nil {

//            print("nil")

//        }

//        else {

//            print("no nil")

//        }

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

        return newsJson!.count

    }

    

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {

        

//寻找三个类里面不同的地方,第一个是一张图,第二个很多图,第三个有decs

        let json = newsJson![indexPath.row]

        if json["image"] != nil {

            let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell

//            cell.coverImageView.kf_setImageWithURL(NSURL(string: json["image"].string!))

            cell.showInfo(json)

            return cell

        }

        else if json["images"] != nil {

            let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as! SecondTableViewCell

            return cell

        }

        else {

            let cell = tableView.dequeueReusableCellWithIdentifier("cell3", forIndexPath: indexPath) as! ThirdTableViewCell

            return cell

        }

        

#if false

        //求余(求模, mode)

        if indexPath.row % 2 == 0 {

            //1. 获取可以重用的Cell对象

            //2. 根据重用标识创建Cell

            let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as! SecondTableViewCell

            

            cell.rightImageView.image = UIImage(named: "1.jpg")

            

            return cell

        }

        else {

            //1. 获取可以重用的Cell对象

            //2. 根据重用标识创建Cell

            let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell

            

            cell.coverImageView.image = UIImage(named: "1.jpg")

            

            return cell

        }

#endif

    }

    

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath:NSIndexPath) -> CGFloat {

        return 80

    }

    

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {

//        let json = newsJson![indexPath.row]

//        let cell = tableView.cellForRowAtIndexPath(indexPath)

    }

}

创建的第一个类

import UIKit
import SwiftyJSON
import Kingfisher

class CustomTableViewCell: UITableViewCell {

    var coverImageView: UIImageView!
    var model: JSON?

    //创建Cell时,无法获取Cell的尺寸

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        //先调用父类中的init方法

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        

        coverImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 50, height:60))

        self.contentView.addSubview(coverImageView)

    }

    

    //所有UIView的子类,必须实现。用于Storyboard中加载该控件时

    required init?(coder aDecoder: NSCoder) {

        //直接让程序崩溃

        fatalError("init(coder:) has not been implemented. ")

    }

    func showInfo(model: JSON) {

        self.model = model

        coverImageView.kf_setImageWithURL(NSURL(string: model["image"].string!))

    }

}

创建的第二个类

import UIKit

class SecondTableViewCell: UITableViewCell {

    var rightImageView: UIImageView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        //不合适,Cell不一定充满整个屏幕,应该用自动布局

//        let screenWidth = UIScreen.mainScreen().bounds.size.width

        rightImageView = UIImageView()

        self.contentView.addSubview(rightImageView)

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    //重点

    //当View本身显示或者位置、大小发生改变时,自动调用

    //时机:应该计算子视图的位置和大小

    override func layoutSubviews() {

        //如果不是想替换父类中方法的功能,而只是增加功能,应该使用super调用父类的方法

        super.layoutSubviews()
   

        //self的位置和尺寸一定已经确定了

        rightImageView.frame = CGRectMake(self.frame.size.width - 50 - 10, 10, 50, 60)

    }

}

创建的第三个类

import UIKit

class ThirdTableViewCell: UITableViewCell {

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }

    override func setSelected(selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state

    }

}

JSON数据

[

 {

    "title":"太原3.1级地震",

    "date":"今天 19:36",

   "image":"http://hbimg.b0.upaiyun.com/bdb56d4ab6cfd271cce1ed5b7a061107f8d7e64f11bd4-GQdkR4_fw658"

 },

 {

    "title":"4名大学生花4k装修文艺宿舍",

    "date":"今天 19:14",

    "images":[

        "http://hbimg.b0.upaiyun.com/fe97ed0e06db1e3159423bc54e1dda27536f0efe62d24-lCissl_fw658",

        "http://hbimg.b0.upaiyun.com/39475d88b745e98d2401d8809389263f64872f2d21164-1kg2YR_fw658",

        "http://hbimg.b0.upaiyun.com/409d16281c8057b286a2dd3d6e95a6bf4cb77e9e5c19b-o42VRv_fw658"

    ]

 },

 {

    "title":"工商总局局长接受凤凰专访 首谈商事制度改革之困",

    "date":"今天 19:04",

    "desc":"国家工商总局局长张茅日前在接受凤凰卫视《问答神州》栏目专访时,直面吴小莉就商事制度改革之问——“改革阻力和难度在哪里?”"

 }

]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,419评论 4 61
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,833评论 19 139
  • 最大的印象就是被野狗追,然后用木棍丢去打它,好像是回到一个有点像以前还没有修河堤的王家镇,让很多路啊河流啊都跟我小...
    向上的潘达阅读 1,495评论 0 0
  • 目录 上一章 中考失利 第二章 忆起伤心的往事 路峰平时很少过问路一鸣在校的学习生活,他仅仅在乎儿子路一鸣每次的考...
    青梅梦语阅读 3,161评论 1 7
  • 过年期间我和爸爸妈妈一起去见了他们好久不见的老朋友。 一路上,爸妈说着他们的回忆。阿姨有先天性的心脏病,叔...
    闲杂人儿L阅读 4,739评论 0 0

友情链接更多精彩内容