本文的例子和Swift版本是基于Xcode7.2的。以后也許不知道什么時(shí)候會(huì)更新。
我們要干點(diǎn)啥
用新浪微博的Open API做后端來(lái)實(shí)現(xiàn)我們要提到的功能。把新浪微博的內(nèi)容,圖片和文字展示在collection view中。本文只簡(jiǎn)單的展示內(nèi)容。下篇會(huì)用pinterest一樣的效果來(lái)展示這些內(nèi)容。
我們準(zhǔn)備優(yōu)先展示圖片。你的好友花了那么多時(shí)間拍照或者從相冊(cè)里選擇圖片發(fā)上來(lái)多不容易。如果微博返回的數(shù)據(jù)中有中等大小的縮略圖,那么久展示這個(gè)縮略圖。否則的話(huà)顯示文本。文本都沒(méi)有的話(huà)。。。這個(gè)就不是微博了。但是我們還是會(huì)準(zhǔn)備一個(gè)顏色顯示出來(lái)。
啥是UICollectionView
UICollectionView有一個(gè)靈活的布局,可以用各種不同的布局展示數(shù)據(jù)。
UICollectionView的使用和UITableView類(lèi)似,也是需要分別去實(shí)現(xiàn)一組datasource的代理和UICollectionView本身的代理來(lái)把數(shù)據(jù)展示在界面中。
UICollectionView也是UIScrollView的一個(gè)子類(lèi)
其他的還有:
- UICollectionViewCell:這些Cell組成了整個(gè)UICollectionView,并作為子View添加到UICollectionView中。可以在Interface builder中創(chuàng)建,也可以代碼創(chuàng)建。
- Header/Footer:跟UITableView差不多的概念。顯示一些title什么的信息。
UICollectionView還有一個(gè)叫做Decoration view的東西。顧名思義,主要是裝飾用的。
不過(guò)要用這部分的功能你需要單獨(dú)寫(xiě)定制的layout。
除了以上說(shuō)到的內(nèi)容之外,collection view還有一個(gè)專(zhuān)門(mén)處理布局的UICollectionViewLayout
。你可以繼承UICollectionViewLayout
來(lái)創(chuàng)建一個(gè)自己的collection view的布局。蘋(píng)果給了一個(gè)基礎(chǔ)的布局UICollectionViewFlowLayout
,可以實(shí)現(xiàn)一個(gè)基本的流式布局。這些會(huì)在稍后的教程中介紹。
開(kāi)始我們的項(xiàng)目:
首先創(chuàng)建一個(gè)single view的應(yīng)用。
然后給你的項(xiàng)目起一個(gè)名字,我們這里就叫做CollectionViewDemo
。Storyboard中默認(rèn)生成的Controller已經(jīng)木有什么用處了。直接干掉,拖一個(gè)UICollectionViewController
進(jìn)去并設(shè)置為默認(rèn)的Controller。并刪除默認(rèn)生成的ViewController.swift文件,并創(chuàng)建一個(gè)叫做HomeCollectionViewController.swift的文件。之后在interface builder中把collection view的類(lèi)設(shè)置為HomeCollectionViewController
。
然后:
- 在Storyboard中添加一個(gè)navigation controller
- 把collection view設(shè)置為上面的navigation controller的root view controller。
- 把這個(gè)navigation controller設(shè)置為initial view controller。
接下來(lái)再次回到collection view controller。這個(gè)
進(jìn)一步了解UICollectionView
如前文所述,UICollectionView和UITableView類(lèi)似,都有datasource和delegate。這樣就可以設(shè)置datasource和設(shè)置一些用戶(hù)的交互,比如選中某一個(gè)cell的時(shí)候怎么處理。
UICollectionViewFlowLayout
有一個(gè)代理:UICollectionViewDelegateFlowLayout
。通過(guò)這個(gè)代理可以設(shè)定布局的一些行為比如:cell的間隔,collection view的滾動(dòng)方向等。
下面就開(kāi)始在我們的代碼中給UICollectionViewDataSource
和UICollectionViewDelegateFlowLayout
兩個(gè)代理的方法做一個(gè)填空。UICollectionViewDelegate
里的方法暫時(shí)還用不著,稍后會(huì)給這個(gè)代理做填空。
實(shí)現(xiàn)UICollectionViewDataSource
這里我們用微博開(kāi)放API為例。從微博的開(kāi)發(fā)API上獲取到當(dāng)前用戶(hù)的全部的微博,然后用UICollectionView展示。獲取到的微博time line最后會(huì)放在這里:
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
}
- 我們只要一個(gè)section,所以這里返回?cái)?shù)字1。
- 返回的time line都會(huì)放在類(lèi)型為
StatusModel
的數(shù)組里。這個(gè)數(shù)組可能為空,因?yàn)楹芏嗲闆r會(huì)影響到網(wǎng)絡(luò)請(qǐng)求,比如網(wǎng)絡(luò)不通的時(shí)候。這個(gè)時(shí)候返回的time line就是空了。所以self.timeLineStatus?.count
得出的數(shù)字也可能是空,那么這個(gè)時(shí)候就應(yīng)該返回0。 - 由于沒(méi)有合適的Cell返回,現(xiàn)在只好用改變Cell的背景色的方式看到Cell的排布。
效果是這樣的:
UICollectionViewFlowLayoutDelegate
這個(gè)代理的作用和UITableView的func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
有非常類(lèi)似的作用。heightForRowAtIndexPath
的作用是返回UITableViewCell的高度。而UICollectionViewCell有非常多的不同的大小,所以需要更加復(fù)雜的代理方法的支持。其中包括兩個(gè)方法:
// 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
}
- 首先需要實(shí)現(xiàn)layout的代理
UICollectionViewDelegateFlowLayout
。 - 給類(lèi)添加一個(gè)
sectionInsets
的屬性。 -
UICollectionViewDelegateFlowLayout
的第一個(gè)方法,用來(lái)返回indexPath
指定位置的Cell的Size。 - layout代理的另外一個(gè)方法,用來(lái)返回每一個(gè)section的inset。
看看運(yùn)行效果:
創(chuàng)建自定義UICollectionViewCell
下面就要處理內(nèi)容在展示的時(shí)候具體應(yīng)該怎么展示了。我們這里分兩種情況,如果用戶(hù)的微博有圖片,那么就展示圖片。如果沒(méi)有圖片就展示文字。可惜的是微博的API沒(méi)有圖片的大小返回回來(lái)。展示的時(shí)候需要大小參數(shù)來(lái)決定這個(gè)
UICollectionViewCell
到底要多大的size,由于沒(méi)有就只好弄個(gè)方塊來(lái)展示圖片了。至于圖片的拉伸方式就有你來(lái)決定了,我們這里為了簡(jiǎn)單就使用默認(rèn)的方式拉伸圖片。
在文字上就需要根據(jù)文字的多少了決定size了。由于我們的寬度是一定的,也就是說(shuō)在autolayout中UILabel
的preferredMaxLayoutWidth
是一定的。然后就可以很方便的根據(jù)這個(gè)寬度來(lái)計(jì)算多行的UILabel
到底需要多少的高度來(lái)全部展示微博中的文字。
首先是展示圖片的Cell。
在Cell上放一個(gè)
UIImageView
,保證這個(gè)image view的四個(gè)邊距都是0。
創(chuàng)建一個(gè)文件WeiboImageCell.swift,里面是類(lèi)WeiboImageCell
,繼承自UICollectionViewCell
。
把這個(gè)Cell的custom class設(shè)置為
WeiboImageCell
。然后把Cell代碼中的image view和interface builder的image view關(guān)聯(lián)為IBOutelt:
class WeiboImageCell: UICollectionViewCell {
@IBOutlet weak var weiboImageView: UIImageView!
}
重復(fù)上面的步驟添加一個(gè)只有一個(gè)UILabel
的Cell,類(lèi)型為WeiboTextCell
。設(shè)置這個(gè)UILabel
的屬性numberOfLines
為0,這樣就可以顯示多行的文字。然后設(shè)置這個(gè)label的上、左、下、右都是-8。
為什么是-8呢,因?yàn)樘O(píng)果默認(rèn)的給父view留了寬度為8的margin(邊距),如果要文字和Cell的邊距貼合的話(huà)
需要覆蓋這個(gè)系統(tǒng)預(yù)留的邊距,因此需要設(shè)置邊距為-8。
最后關(guān)聯(lián)代碼和label。
class WeiboTextCell: UICollectionViewCell {
@IBOutlet weak var weiboTextLabel: UILabel!
}
添加完這兩個(gè)Cell之后,回到HomeCollectionViewController
。刪除self.collectionView!.registerClass(WeiboImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)
方法,以及全部的registerClass
。
`registerClass`, 這個(gè)方法的調(diào)用會(huì)把我們?cè)趕toryboard里做的一切都給抹掉。在調(diào)用Cell里的image view或者label的時(shí)候得到的永遠(yuǎn)是nil。
到這,我們需要討論一下text cell對(duì)于label的約束問(wèn)題。首先我們同樣設(shè)置label的約束,讓這個(gè)label貼著cell的邊。也就是,top、leading、trailing和bottom為-8。
但是這樣的而設(shè)置讓label在顯示出來(lái)的cell中是居中的。尤其在文字不足夠現(xiàn)實(shí)滿(mǎn)cell的空間的時(shí)候。所以,我們需要改一個(gè)地方。修改bottom的優(yōu)先級(jí),設(shè)置為low,最低:UILayoutPriorityDefaultLow
。這樣在labe計(jì)算高度的時(shí)候會(huì)優(yōu)先考慮的是文字填滿(mǎn)label后的高度,而不是像之前一樣直接把labe的高度設(shè)置為cell的高度。這個(gè)時(shí)候不論文字是否填滿(mǎn)cell,都是從頂開(kāi)始顯示有多少控件用多少空間。
集成SDWebImage
我們那什么來(lái)拯救圖片cell惹?辣就是SDWebImage
是一個(gè)著名的圖片請(qǐng)求和緩存的庫(kù)。我們這里用這個(gè)庫(kù)來(lái)請(qǐng)求微博中的圖片并緩存。
添加:
在Podfile里添加SDWebImage
的pod應(yīng)用pod 'SDWebImage', '~>3.7'。當(dāng)然了之前我們已經(jīng)添加了user_frameworks!
。為什么用這個(gè)看原文:
You can make CocoaPods integrate to your project via frameworks
instead of static libraries by specifying use_frameworks!.
多了就不多說(shuō)了,需要了解更多的可以看這里。
pod更新完成之后。引入這個(gè)framework。
import SDWebImage
然后就可以給cell的image view上圖片了。
weiboImageCell.weiboImageView.sd_setImageWithURL(NSURL(string: status.status?.bmiddlePic ?? ""))
SDWebImage
給image view寫(xiě)了一個(gè)category。里面有很多可以調(diào)用的方法。比如可以設(shè)置一個(gè)place holder的image。也就是在image沒(méi)有下載下來(lái)之前可以給image view設(shè)置一個(gè)默認(rèn)的圖片。
http請(qǐng)求和數(shù)據(jù)
這里只是簡(jiǎn)單說(shuō)一下,更過(guò)的內(nèi)容請(qǐng)看這里。
下面我們看看微博的Open API能給我們返回什么:
{
"statuses": [
{
"created_at": "Tue May 31 17:46:55 +0800 2011",
"id": 11488058246,
"text": "求關(guān)注。",
"source": "<a 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": "北京 朝陽(yáng)區(qū)",
"description": "人生五十年,乃如夢(mèng)如幻;有生斯有死,壯士復(fù)何憾。",
"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, // 暫時(shí)不支持
"next_cursor": 11488013766, // 暫時(shí)不支持
"total_number": 81655
}
我們只需要我們follow的好友的微博的圖片或者文字。所以由這些內(nèi)容我們可以定義出對(duì)應(yīng)的model類(lèi)。
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"]
}
}
其中內(nèi)容全部都放在類(lèi)StatusModel
中,圖片我們用屬性bmiddlePic
,文字用weiboText
。其他屬性留著以后使用。
請(qǐng)求完成以后,這些time line的微博會(huì)存在一個(gè)屬性里做為數(shù)據(jù)源使用。
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()
}
})
}
- 存放數(shù)據(jù)源的屬性。
-
Alamofire
發(fā)出http請(qǐng)求。 - 請(qǐng)求成功之后解析數(shù)據(jù),并把我們需要的微博數(shù)據(jù)存放在屬性
self.timeLineStatus
。
在展示數(shù)據(jù)的時(shí)候需要區(qū)分微博的圖片是否存在,存在則優(yōu)先展示圖片,否則展示文字。
一個(gè)不怎么好的做法是在方法cell for collection view里判斷數(shù)據(jù)源是否存在,遍歷每一個(gè)數(shù)據(jù)源的item判斷這個(gè)item是否有圖片。。。
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let statuses = self.timeLineStatus {
let status = statuses[indexPath.item]
if status
}
}
這樣顯然太過(guò)冗長(zhǎng)了,所以我們要把這一部分代碼提升出來(lái)。
/**
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是可以在一個(gè)方法里返回多個(gè)值的。這個(gè)多個(gè)內(nèi)容的值用tuple
來(lái)存放。調(diào)用時(shí)這樣的:
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
只要通過(guò)let hasImage = status?.hasImage
就可以判斷是否有圖片。所以Swift的這一點(diǎn)還是非常方便的。那么在判斷要顯示哪一種Cell的時(shí)候就非常的方便了。修改后的代碼也非常的簡(jiǎn)潔。這個(gè)習(xí)慣需要一直保持下去。
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
}
跑起來(lái),看看運(yùn)行效果。
好丑!!!
全部代碼在這里