zoukankan      html  css  js  c++  java
  • Swift:用UICollectionView整一个瀑布流

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

    我们要干点啥

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

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

    啥是UICollectionView

    UICollectionView有一个灵活的布局,可以用各种不同的布局展示数据。 
    UICollectionView的使用和UITableView类似,也是需要分别去实现一组datasource的代理和UICollectionView本身的代理来把数据展示在界面中。

    UICollectionView也是UIScrollView的一个子类

    其他的还有: 
    1. UICollectionViewCell:这些Cell组成了整个UICollectionView,并作为子View添加到UICollectionView中。可以在Interface builder中创建,也可以代码创建。 
    2. Header/Footer:跟UITableView差不多的概念。显示一些title什么的信息。

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

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

    开始我们的项目: 
    首先创建一个single view的应用。 

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

    然后: 

    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( 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

     
     
     
     
     
  • 相关阅读:
    微信小程序之坑(一) JESSIONID一直变动问题
    spring 异常org.springframework.dao.IncorrectResultSizeDataAccessException: query did not return a unique result: 2
    springdatajpa之坑(一)
    AOP实战
    spingboot pom文件 打成war 包 热部署 引入第三方jar包
    javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session 解决办法
    判断请求来自手机还是PC
    存储过程
    jfinal 连接oracle 数据库把外键当成主键 在mappingkit文件里生成多个主键解决办法
    oracle 回复以前的数据
  • 原文地址:https://www.cnblogs.com/sunshine-anycall/p/5171381.html
Copyright © 2011-2022 走看看