Swift:用UICollectionView整一个瀑布流
本文的例子和Swift版本是基于Xcode7.2的。以后也许不知道什么时候会更新。 我们要干点啥用新浪微博的Open API做后端来实现我们要提到的功能。把新浪微博的内容,图片和文字展示在collection view中。本文只简单的展示内容。下篇会用pinterest一样的效果来展示这些内容。 我们准备优先展示图片。你的好友花了那么多时间拍照或者从相册里选择图片发上来多不容易。如果微博返回的数据中有中等大小的缩略图,那么久展示这个缩略图。否则的话显示文本。文本都没有的话。。。这个就不是微博了。但是我们还是会准备一个颜色显示出来。 啥是UICollectionViewUICollectionView有一个灵活的布局,可以用各种不同的布局展示数据。 UICollectionView也是UIScrollView的一个子类
其他的还有: UICollectionView还有一个叫做Decoration view的东西。顾名思义,主要是装饰用的。
不过要用这部分的功能你需要单独写定制的layout。
除了以上说到的内容之外,collection view还有一个专门处理布局的 开始我们的项目: 然后给你的项目起一个名字,我们这里就叫做 然后:
接下来再次回到collection view controller。这个 进一步了解UICollectionView如前文所述,UICollectionView和UITableView类似,都有datasource和delegate。这样就可以设置datasource和设置一些用户的交互,比如选中某一个cell的时候怎么处理。
下面就开始在我们的代码中给 实现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
}
效果是这样的: UICollectionViewFlowLayoutDelegate这个代理的作用和UITableView的 // 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
}
看看运行效果: 创建自定义UICollectionViewCell下面就要处理内容在展示的时候具体应该怎么展示了。我们这里分两种情况,如果用户的微博有图片,那么就展示图片。如果没有图片就展示文字。可惜的是微博的API没有图片的大小返回回来。展示的时候需要大小参数来决定这个 在文字上就需要根据文字的多少了决定size了。由于我们的宽度是一定的,也就是说在autolayout中 首先是展示图片的Cell。 创建一个文件WeiboImageCell.swift,里面是类 class WeiboImageCell: UICollectionViewCell {
@IBOutlet weak var weiboImageView: UIImageView!
}
重复上面的步骤添加一个只有一个 为什么是-8呢,因为苹果默认的给父view留了宽度为8的margin(边距),如果要文字和Cell的边距贴合的话
需要覆盖这个系统预留的边距,因此需要设置边距为-8。
最后关联代码和label。 class WeiboTextCell: UICollectionViewCell {
@IBOutlet weak var weiboTextLabel: UILabel!
}
添加完这两个Cell之后,回到 `registerClass`, 这个方法的调用会把我们在storyboard里做的一切都给抹掉。在调用Cell里的image view或者label的时候得到的永远是nil。
到这,我们需要讨论一下text cell对于label的约束问题。首先我们同样设置label的约束,让这个label贴着cell的边。也就是,top、leading、trailing和bottom为-8。 但是这样的而设置让label在显示出来的cell中是居中的。尤其在文字不足够现实满cell的空间的时候。所以,我们需要改一个地方。修改bottom的优先级,设置为low,最低: 集成SDWebImage我们那什么来拯救图片cell惹?辣就是 添加: 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 ?? ""))
http请求和数据这里只是简单说一下,更过的内容请看这里。 {
"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"] } }
其中内容全部都放在类 请求完成以后,这些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()
}
})
}
在展示数据的时候需要区分微博的图片是否存在,存在则优先展示图片,否则展示文字。 一个不怎么好的做法是在方法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是可以在一个方法里返回多个值的。这个多个内容的值用 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
只要通过 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(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |