收藏查看Swift 4-iOS11
今天,我们将在Swift 4 iOS 11 Xcode 9中讨论集合视图,
步骤1:建立新的Xcode专案
步骤2:创建MVC文件夹(Model View Controller)
在controller文件夹中,创建新的可可触摸快速文件(UIViewController),将其命名为MainVC,在View文件夹中,创建新的可可触摸快速文件(UICollectionViewCell)
步骤3:打开Main.Storyboard
从对象库拖动集合视图
将Class CollectionViewCell
连接到我们的单元格
在单元格中添加名为proLbl
Label,并通过单击将其连接,然后在键盘上按Control键并拖动到CollectionViewCell
View中
步骤4:打开Controller — MainVC.swift
将UICollectionViewDataSource
和UICOllectionViewDelegate
添加到类中,然后添加这两个支持功能
func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int {
//返回section
的行数。
}
func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell {
//返回配置的单元格对象。
}
添加一个数组变量以显示collectionViewCell中的数据
//创建一个包含我们的数据的数组
var array = [“第一个单元格”,“第二个单元格”,“第三个单元格”,“第四个单元格”,“第五个单元格”]
编辑numberOfItemsInSection
函数以返回array.count
func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int {
返回array.count
}
编辑cellForRowAt
函数以返回单元格
func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell {
让cell = collectionView.dequeueReusableCell(withReuseIdentifier:“ proCell”,for:indexPath)为! CollectionViewCell
cell.proLbl.text = array [indexPath.row]
返回单元
}
添加名为proCell
的单元格标识符
将Main.Storyboard中的CollectionView与MainVC.swift连接为插座
使用此集合视图出口在viewDidLoad()
连接datasource and delegate
覆盖func viewDidLoad(){
super.viewDidLoad()
proCollectionView.dataSource =自我
proCollectionView.delegate =自我
}
尝试在模拟器中运行应用
谢谢你,祝你有美好的一天
源代码
https://github.com/mohammedjamalhadi/collviewPro.git