具体的代码如下:
import UIKit
let SCREEN_WIDTH = UIScreen.main.bounds.width
class ViewController: UIViewController {
@IBOutlet weak var PictureCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
PictureCollectionView.delegate = self
PictureCollectionView.dataSource = self
}
}
//相当于Android里面的适配器
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 22
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PictureCollectionCell", for: indexPath) as! PictureCollectionCell
cell.testText.text = String(indexPath.row)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//条目点击事件
NSLog("点击了item" + String(indexPath.row))
}
}
//相当于Android里面的ViewHolder,获取列表Item控件,需要在StoryBorad布局CollectionViewCell中设置绑定
class PictureCollectionCell: UICollectionViewCell {
@IBOutlet weak var testText: UILabel!
}
//设置布局配置,需要在CollectionView中设置自定义布局宽高,间距,滑动方式
class CustomCollecionViewFlowLayout: UICollectionViewFlowLayout {
required init?(coder: NSCoder) {
super.init(coder: coder)
scrollDirection = .horizontal
sectionInset = UIEdgeInsets(top: 16, left: 20, bottom: 16, right: 20)
itemSize = CGSize(width: SCREEN_WIDTH/2 - 25, height: SCREEN_WIDTH/2 - 25)
}
}
StoryBoard使用注意点:
1.设置自定义布局
设置自定义布局.png
2.关联控件
关联控件1.png
关联控件2.png
网友评论