Swift:用UICollectionView整一个瀑布流

本文的例子和Swift版本是基于Xcode7.2的。之后也许不知道何时会更新。

咱们要干点啥

用新浪微博的Open API作后端来实现咱们要提到的功能。把新浪微博的内容,图片和文字展现在collection view中。本文只简单的展现内容。下篇会用pinterest同样的效果来展现这些内容。git

咱们准备优先展现图片。你的好友花了那么多时间拍照或者从相册里选择图片发上来多不容易。若是微博返回的数据中有中等大小的缩略图,那么久展现这个缩略图。不然的话显示文本。文本都没有的话。。。这个就不是微博了。可是咱们仍是会准备一个颜色显示出来。github

啥是UICollectionView

UICollectionView有一个灵活的布局,能够用各类不一样的布局展现数据。 
UICollectionView的使用和UITableView相似,也是须要分别去实现一组datasource的代理和UICollectionView自己的代理来把数据展现在界面中。web

UICollectionView也是UIScrollView的一个子类

其余的还有: 
1. UICollectionViewCell:这些Cell组成了整个UICollectionView,并做为子View添加到UICollectionView中。能够在Interface builder中建立,也能够代码建立。 
2. Header/Footer:跟UITableView差很少的概念。显示一些title什么的信息。json

UICollectionView还有一个叫作Decoration view的东西。顾名思义,主要是装饰用的。
不过要用这部分的功能你须要单独写定制的layout。

除了以上说到的内容以外,collection view还有一个专门处理布局的UICollectionViewLayout。你能够继承UICollectionViewLayout来建立一个本身的collection view的布局。苹果给了一个基础的布局UICollectionViewFlowLayout,能够实现一个基本的流式布局。这些会在稍后的教程中介绍。swift

开始咱们的项目: 
首先建立一个single view的应用。 
后端

而后给你的项目起一个名字,咱们这里就叫作CollectionViewDemo。Storyboard中默认生成的Controller已经木有什么用处了。直接干掉,拖一个UICollectionViewController进去并设置为默认的Controller。并删除默认生成的ViewController.swift文件,并建立一个叫作HomeCollectionViewController.swift的文件。以后在interface builder中把collection view的类设置为HomeCollectionViewControllerapi

而后: 
数组

  1. 在Storyboard中添加一个navigation controller
  2. 把collection view设置为上面的navigation controller的root view controller。
  3. 把这个navigation controller设置为initial view controller。

接下来再次回到collection view controller。这个缓存

进一步了解UICollectionView

如前文所述,UICollectionView和UITableView相似,都有datasource和delegate。这样就能够设置datasource和设置一些用户的交互,好比选中某一个cell的时候怎么处理。网络

UICollectionViewFlowLayout有一个代理:UICollectionViewDelegateFlowLayout。经过这个代理能够设定布局的一些行为好比:cell的间隔,collection view的滚动方向等。

下面就开始在咱们的代码中给UICollectionViewDataSourceUICollectionViewDelegateFlowLayout 两个代理的方法作一个填空。UICollectionViewDelegate里的方法暂时还用不着,稍后会给这个代理作填空。

实现UICollectionViewDataSource

这里咱们用微博开放API为例。从微博的开发API上获取到当前用户的所有的微博,而后用UICollectionView展现。获取到的微博time line最后会放在这里:

private var timeLineStatus: [StatusModel]?

在data source中的代码就很好添加了。

// MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1    //1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.timeLineStatus?.count ?? 0 //2
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)

        cell.backgroundColor = UIColor.orangeColor() //3

        return cell
    }
  1. 咱们只要一个section,因此这里返回数字1。
  2. 返回的time line都会放在类型为StatusModel的数组里。这个数组可能为空,由于不少状况会影响到网络请求,好比网络不通的时候。这个时候返回的time line就是空了。因此self.timeLineStatus?.count得出的数字也多是空,那么这个时候就应该返回0。
  3. 因为没有合适的Cell返回,如今只好用改变Cell的背景色的方式看到Cell的排布。

效果是这样的: 

UICollectionViewFlowLayoutDelegate

这个代理的做用和UITableView的func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat有很是相似的做用。heightForRowAtIndexPath的做用是返回UITableViewCell的高度。而UICollectionViewCell有很是多的不一样的大小,因此须要更加复杂的代理方法的支持。其中包括两个方法:

// 1
class HomeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout 

// 2
private let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) 

// MARK: UICollectionViewDelegateFlowLayout

// 3
func collectionView(collectionView: UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 170, height: 300)
}

// 4
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return sectionInsets
}
  1. 首先须要实现layout的代理UICollectionViewDelegateFlowLayout
  2. 给类添加一个sectionInsets的属性。
  3. UICollectionViewDelegateFlowLayout的第一个方法,用来返回indexPath指定位置的Cell的Size。
  4. layout代理的另一个方法,用来返回每个section的inset。

看看运行效果: 

建立自定义UICollectionViewCell

下面就要处理内容在展现的时候具体应该怎么展现了。咱们这里分两种状况,若是用户的微博有图片,那么就展现图片。若是没有图片就展现文字。惋惜的是微博的API没有图片的大小返回回来。展现的时候须要大小参数来决定这个 
UICollectionViewCell到底要多大的size,因为没有就只好弄个方块来展现图片了。至于图片的拉伸方式就有你来决定了,咱们这里为了简单就使用默认的方式拉伸图片。

在文字上就须要根据文字的多少了决定size了。因为咱们的宽度是必定的,也就是说在autolayout中UILabelpreferredMaxLayoutWidth是必定的。而后就能够很方便的根据这个宽度来计算多行的UILabel到底须要多少的高度来所有展现微博中的文字。

首先是展现图片的Cell。 

在Cell上放一个UIImageView,保证这个image view的四个边距都是0。

建立一个文件WeiboImageCell.swift,里面是类WeiboImageCell,继承自UICollectionViewCell。 

把这个Cell的custom class设置为WeiboImageCell。 
 
而后把Cell代码中的image view和interface builder的image view关联为IBOutelt

class WeiboImageCell: UICollectionViewCell {
    @IBOutlet weak var weiboImageView: UIImageView!
}

重复上面的步骤添加一个只有一个UILabel的Cell,类型为WeiboTextCell。设置这个UILabel的属性numberOfLines为0,这样就能够显示多行的文字。而后设置这个label的上、左、下、右都是-8。

为何是-8呢,由于苹果默认的给父view留了宽度为8的margin(边距),若是要文字和Cell的边距贴合的话 须要覆盖这个系统预留的边距,所以须要设置边距为-8。

最后关联代码和label。

class WeiboTextCell: UICollectionViewCell {
    @IBOutlet weak var weiboTextLabel: UILabel!
}

添加完这两个Cell以后,回到HomeCollectionViewController。删除self.collectionView!.registerClass(WeiboImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)方法,以及所有的registerClass

`registerClass`, 这个方法的调用会把咱们在storyboard里作的一切都给抹掉。在调用Cell里的image view或者label的时候获得的永远是nil。

到这,咱们须要讨论一下text cell对于label的约束问题。首先咱们一样设置label的约束,让这个label贴着cell的边。也就是,top、leading、trailing和bottom为-8。

可是这样的而设置让label在显示出来的cell中是居中的。尤为在文字不足够现实满cell的空间的时候。因此,咱们须要改一个地方。修改bottom的优先级,设置为low,最低:UILayoutPriorityDefaultLow。这样在labe计算高度的时候会优先考虑的是文字填满label后的高度,而不是像以前同样直接把labe的高度设置为cell的高度。这个时候不论文字是否填满cell,都是从顶开始显示有多少控件用多少空间。

集成SDWebImage

咱们那什么来拯救图片cell惹?辣就是SDWebImage是一个著名的图片请求和缓存的库。咱们这里用这个库来请求微博中的图片并缓存。

添加: 
Podfile里添加SDWebImage的pod应用pod ‘SDWebImage’, ‘~>3.7’。固然了以前咱们已经添加了user_frameworks!。为何用这个看原文:

You can make CocoaPods integrate to your project via frameworks instead of static libraries by specifying use_frameworks!. 

多了就很少说了,须要了解更多的能够看这里

pod更新完成以后。引入这个framework。

import SDWebImage

而后就能够给cell的image view上图片了。

weiboImageCell.weiboImageView.sd_setImageWithURL(NSURL(string: status.status?.bmiddlePic ?? ""))

SDWebImage给image view写了一个category。里面有不少能够调用的方法。好比能够设置一个place holder的image。也就是在image没有下载下来以前能够给image view设置一个默认的图片。

http请求和数据

这里只是简单说一下,更过的内容请看这里。 
下面咱们看看微博的Open API能给咱们返回什么:

{
    "statuses": [
        {
            "created_at": "Tue May 31 17:46:55 +0800 2011",
            "id": 11488058246,
            "text": "求关注。",
            "source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
            "favorited": false,
            "truncated": false,
            "in_reply_to_status_id": "",
            "in_reply_to_user_id": "",
            "in_reply_to_screen_name": "",
            "geo": null,
            "mid": "5612814510546515491",
            "reposts_count": 8,
            "comments_count": 9,
            "annotations": [],
            "user": {
                "id": 1404376560,
                "screen_name": "zaku",
                "name": "zaku",
                "province": "11",
                "city": "5",
                "location": "北京 朝阳区",
                "description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。",
                "url": "http://blog.sina.com.cn/zaku",
                "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
                "domain": "zaku",
                "gender": "m",
                "followers_count": 1204,
                ...
            }
        },
        ...
    ],
    "ad": [
        {
            "id": 3366614911586452,
            "mark": "AB21321XDFJJK"
        },
        ...
    ],
    "previous_cursor": 0,      // 暂时不支持
    "next_cursor": 11488013766,     // 暂时不支持
    "total_number": 81655
}

咱们只须要咱们follow的好友的微博的图片或者文字。因此由这些内容咱们能够定义出对应的model类。

import ObjectMapper

class BaseModel: Mappable {
    var previousCursor: Int?
    var nextCursor: Int?
    var hasVisible: Bool?
    var statuses: [StatusModel]?
    var totalNumber: Int?

    required init?(_ map: Map) {

    }

    func mapping(map: Map) {
        previousCursor <- map["previous_cursor"]
        nextCursor <- map["next_cursor"]
        hasVisible <- map["hasvisible"]
        statuses <- map["statuses"]
        totalNumber <- map["total_number"]
    }
}

import ObjectMapper

class StatusModel: BaseModel {
    var statusId: String?
    var thumbnailPic: String?
    var bmiddlePic: String?
    var originalPic: String?
    var weiboText: String?
    var user: WBUserModel?

    required init?(_ map: Map) {
        super.init(map)

    }

    override func mapping(map: Map) {
        super.mapping(map)
        statusId <- map["id"]
        thumbnailPic <- map["thumbnail_pic"]
        bmiddlePic <- map["bmiddle_pic"]
        originalPic <- map["original_pic"]
        weiboText <- map["text"]
    }
}

其中内容所有都放在类StatusModel中,图片咱们用属性bmiddlePic,文字用weiboText。其余属性留着之后使用。

请求完成之后,这些time line的微博会存在一个属性里作为数据源使用。

class HomeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
  private var timeLineStatus: [StatusModel]?  // 1

  //2
  Alamofire.request(.GET, "https://api.weibo.com/2/statuses/friends_timeline.json", parameters: parameters, encoding: .URL, headers: nil)
                .responseString(completionHandler: {response in
                    let statuses = Mapper<BaseModel>().map(response.result.value)

                    if let timeLine = statuses where timeLine.totalNumber > 0 {
                        self.timeLineStatus = timeLine.statuses // 3
                        self.collectionView?.reloadData()
                    }
            })
}
  1. 存放数据源的属性。
  2. Alamofire发出http请求。
  3. 请求成功以后解析数据,并把咱们须要的微博数据存放在属性self.timeLineStatus

在展现数据的时候须要区分微博的图片是否存在,存在则优先展现图片,不然展现文字。

一个不怎么好的作法是在方法cell for collection view里判断数据源是否存在,遍历每个数据源的item判断这个item是否有图片。。。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  if let statuses = self.timeLineStatus {
    let status = statuses[indexPath.item]
    if status 
  }
}

这样显然太过冗长了,因此咱们要把这一部分代码提高出来。

/**
     get status and if this status has image or not
     @return:
        status, one of the timeline
        Int, 1: there's image, 0: there's no image, -1: empty status
     */
    func getWeiboStatus(indexPath: NSIndexPath) -> (status: StatusModel?, hasImage: Int) {  // 1
        if let timeLineStatusList = self.timeLineStatus where timeLineStatusList.count > 0 {
            let status = timeLineStatusList[indexPath.item]
            if let middlePic = status.bmiddlePic where middlePic != "" {
                // there's middle sized image to show
                return (status, 1)

            } else {
                // start to consider text
                return (status, 0)
            }
        }

        return (nil, -1)
    }

swift是能够在一个方法里返回多个值的。这个多个内容的值用tuple来存放。调用时这样的:

let status = self.getWeiboStatus(indexPath)
let hasImage = status?.hasImage              // if there's a image 
let imageUrl = status.status?.bmiddlePic     // image path
let text = status.status?.weiboText          // text

只要经过let hasImage = status?.hasImage就能够判断是否有图片。因此Swift的这一点仍是很是方便的。那么在判断要显示哪种Cell的时候就很是的方便了。修改后的代码也很是的简洁。这个习惯须要一直保持下去。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let status = self.getWeiboStatus(indexPath)
        var cell: UICollectionViewCell = UICollectionViewCell()

        guard let _ = status.status else {
            cell.backgroundColor = UIColor.darkTextColor()
            return cell
        }

        if status.hasImage == 1 {
            cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
            let weiboImageCell = cell as! WeiboImageCell
            weiboImageCell.weiboImageView.backgroundColor = UIColor.blueColor()
            weiboImageCell.weiboImageView.sd_setImageWithURL(NSURL(string: status.status?.bmiddlePic ?? ""))

        } else if status.hasImage == 0 {
            cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseTextIdentifier, forIndexPath: indexPath)
            let weiboTextCell = cell as! WeiboTextCell
            weiboTextCell.setCellWidth(self.cellWidth)
            weiboTextCell.weiboTextLabel.text = status.status?.weiboText ?? ""
            weiboTextCell.contentView.backgroundColor = UIColor.orangeColor()
            weiboTextCell.weiboTextLabel.backgroundColor = UIColor.redColor()
        } else {
            cell = UICollectionViewCell()
        }

        cell.backgroundColor = UIColor.orangeColor() //3

        return cell
    }

跑起来,看看运行效果。 
这里写图片描述

好丑!!!

 

所有代码在这里

to be continued

相关文章
相关标签/搜索