swift CollectionView

原文地址

定義collectionView的布局類型张吉,流式布局

let layout = UICollectionViewFlowLayout()

設(shè)置item(cell)的大小

layout.itemSize = CGSize(width: width/2, height: height/3)

設(shè)置滑動(dòng)方向

/**

默認(rèn)方向是垂直

UICollectionViewScrollDirection.vertical? 省略寫(xiě)法是.vertical

水平方向

UICollectionViewScrollDirection.horizontal 省略寫(xiě)法是.horizontal

*/

layout.scrollDirection = .vertical

設(shè)置每個(gè)item之間最小的間距

layout.minimumInteritemSpacing = 0

設(shè)置每行之間最小的間距

layout.minimumLineSpacing = 0

定義一個(gè)UICollectionView

let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: width, height: height), collectionViewLayout: layout)

collectionView.backgroundColor = UIColor.red

設(shè)置collectionView的代理 (注意:設(shè)置完代理之后會(huì)有錯(cuò)誤,原因是代理的必要方法沒(méi)有實(shí)現(xiàn))

collectionView.delegate = self

collectionView.dataSource = self

collectionViewCell的注冊(cè)

collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")

header 的注冊(cè)

collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView")

加載collectionView

self.view.addSubview(collectionView)

實(shí)現(xiàn)collectionView的相關(guān)代理方法

使用關(guān)鍵字extension繼承代理,方法如下

extension MainViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout

numberOfSections方法鲫忍,該方法為 可選 方法,返回sections的個(gè)數(shù)溜族,默認(rèn)return 1

// MARK: UICollectionViewDataSource 代理方法

func numberOfSections(in collectionView: UICollectionView) -> Int {

return 1

}

numberOfItemsInSection方法浓体,該方法為 必選 方法,返回section中item的個(gè)數(shù)

// MARK: UICollectionviewDataSource? 代理方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 8

}

cellForItemAt方法泣刹,該方法為 必選 方法助析,返回繪制collectionView的cell

// MARK: UICollectionviewDataSource? 代理方法

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell

cell.imageView.image = UIImage(named: "\((indexPath as NSIndexPath).row + 2).png")

cell.label.text = "美景\((indexPath as NSIndexPath).row + 1)"

return cell

}

didSelectItemAt方法,該方法為 可選 方法椅您,當(dāng)點(diǎn)擊某個(gè)item之后的響應(yīng)

// MARK: UICollectionViewDelegate的代理方法

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

print("(\((indexPath as NSIndexPath).section), \((indexPath as NSIndexPath).row))")

}

referenceSizeForHeaderInSection方法外冀,該方法為 可選 方法,return: header的大小

// MARK: UICollectionViewDelegateFlowLayout的代理方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

return CGSize(width: width, height: 17)

}

sizeForItemAt方法掀泳,該方法為 可選 方法雪隧,return: item的大小

// MARK: UICollectionViewDelegateFlowLayout的代理方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

if (indexPath as NSIndexPath).row % 2 == 1 {

return CGSize(width: width/2, height: height/3)

}

else {

return CGSize(width: width/2, height: height/2)

}

}

完整代碼

class MainViewController: UIViewController {

// 屏幕的寬和高

let width = UIScreen.main.bounds.width

let height = UIScreen.main.bounds.height

override func viewDidLoad() {

super.viewDidLoad()

// 加載UICollectionView

self.setupCollectionView()

}

// MARK: 加載UICollectionView

func setupCollectionView() {

// 1. 定義collectionView的布局類型西轩,流布局

let layout = UICollectionViewFlowLayout()

// 2. 設(shè)置cell的大小

layout.itemSize = CGSize(width: width/2, height: height/3)

// 3. 滑動(dòng)方向

/**

默認(rèn)方向是垂直

UICollectionViewScrollDirection.vertical? 省略寫(xiě)法是.vertical

水平方向

UICollectionViewScrollDirection.horizontal 省略寫(xiě)法是.horizontal

*/

layout.scrollDirection = .vertical

// 4. 每個(gè)item之間最小的間距

layout.minimumInteritemSpacing = 0

// 5. 每行之間最小的間距

layout.minimumLineSpacing = 0

// 6. 定義一個(gè)UICollectionView

let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: width, height: height), collectionViewLayout: layout)

collectionView.backgroundColor = UIColor.red

// 7. 設(shè)置collectionView的代理和數(shù)據(jù)源

collectionView.delegate = self

collectionView.dataSource = self;

// 8. collectionViewCell的注冊(cè)

collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")

// 9. header 的注冊(cè)

collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView")

self.view.addSubview(collectionView)

}

}

extension MainViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

// MARK: UICollectionViewDataSource 代理方法

/**

該方法為可選方法,默認(rèn)為1

return: collectionView中section的個(gè)數(shù)

*/

func numberOfSections(in collectionView: UICollectionView) -> Int {

return 1

}

// MARK: UICollectionviewDataSource? 代理方法

/**

改方法為必選方法

return: section中的item的個(gè)數(shù)

*/

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 8

}

// MARK: UICollectionviewDataSource? 代理方法

/**

改方法為必選方法

return: 繪制collectionView的cell

*/

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell

cell.imageView.image = UIImage(named: "\((indexPath as NSIndexPath).row + 2).png")

cell.label.text = "美景\((indexPath as NSIndexPath).row + 1)"

return cell

}

// MARK: UICollectionViewDelegate的代理方法

/**

Description: 當(dāng)點(diǎn)擊某個(gè)item之后的回應(yīng)

*/

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

print("(\((indexPath as NSIndexPath).section), \((indexPath as NSIndexPath).row))")

}

// MARK: UICollectionViewDelegateFlowLayout的代理方法

/**

return: header的大小

*/

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

return CGSize(width: width, height: 17)

}

/**

可以定制不同的item

return: item的大小

*/

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

if (indexPath as NSIndexPath).row % 2 == 1 {

return CGSize(width: width/2, height: height/3)

}

else {

return CGSize(width: width/2, height: height/2)

}

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末膀跌,一起剝皮案震驚了整個(gè)濱河市遭商,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌捅伤,老刑警劉巖劫流,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異丛忆,居然都是意外死亡祠汇,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)熄诡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)可很,“玉大人,你說(shuō)我怎么就攤上這事凰浮∥铱伲” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵袜茧,是天一觀的道長(zhǎng)菜拓。 經(jīng)常有香客問(wèn)我,道長(zhǎng)笛厦,這世上最難降的妖魔是什么纳鼎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮裳凸,結(jié)果婚禮上贱鄙,老公的妹妹穿的比我還像新娘。我一直安慰自己姨谷,他們只是感情好逗宁,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著梦湘,像睡著了一般瞎颗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上践叠,一...
    開(kāi)封第一講書(shū)人閱讀 51,631評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音嚼蚀,去河邊找鬼禁灼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛轿曙,可吹牛的內(nèi)容都是我干的弄捕。 我是一名探鬼主播僻孝,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼守谓!你這毒婦竟也來(lái)了穿铆?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤斋荞,失蹤者是張志新(化名)和其女友劉穎荞雏,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體平酿,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凤优,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蜈彼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片筑辨。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖幸逆,靈堂內(nèi)的尸體忽然破棺而出棍辕,到底是詐尸還是另有隱情,我是刑警寧澤还绘,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布楚昭,位于F島的核電站,受9級(jí)特大地震影響蚕甥,放射性物質(zhì)發(fā)生泄漏哪替。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一菇怀、第九天 我趴在偏房一處隱蔽的房頂上張望凭舶。 院中可真熱鬧,春花似錦爱沟、人聲如沸帅霜。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)身冀。三九已至,卻和暖如春括享,著一層夾襖步出監(jiān)牢的瞬間搂根,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工铃辖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留剩愧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓娇斩,卻偏偏與公主長(zhǎng)得像仁卷,于是被迫代替她去往敵國(guó)和親穴翩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容