我想做的效果:
自己看了UICollectionView的教学视频,
根据他的做,自己这样写之后出现了问题。
教程里的是UIImageView,照葫芦画瓢改为了UIButton,出现了问题。
这是教程视频中的代码:
出现的错误:
我写的代码:
在ButtonCell中不像视频教程里那样是Outlet,由于是Button所以选择的是Action。
ViewController里的代码:
import UIKit
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
//储存数据离开阵列,用图像填充字符串
let array:[String] = ["1","2"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//下为集合视图代码
//集合中定义的视图数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count//返回数组,定义量
}
//填充视图
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
//创建可重复使用的
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ButtonCell
cell.buttonCell.button = UIButton(named: array[indexPath.row] + ".JPG") //转换为自定义单元格
return cell//返回单元格`
ButtonCell里的代码:(感觉少了很多,想先把首页做出来)
import UIKit
class ButtonCell: UICollectionViewCell {
@IBAction func buttonCell(_ sender: Any) {
}
}
谢谢各位~
你先搞清楚func 和 属性的区别,按照你的思路,button 是cell上的一个属性,理应在cell里面初始化,而不是放在
cellForItemAt
里面。比如:
然后再
cellForItemAt
里面“