请问如何制作类似Vimeo滑动选择并可以点击的button形式?我用的UICollectionView

我想做的效果:

图片描述

自己看了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) {
    }
}

谢谢各位~

阅读 2.6k
1 个回答

你先搞清楚func 和 属性的区别,按照你的思路,button 是cell上的一个属性,理应在cell里面初始化,而不是放在 cellForItemAt 里面。

比如:

class ButtonCell: UICollectionViewCell {
    var button: UIButton = ...
    func initial {
        addSubview(button)
    }
}

然后再 cellForItemAt 里面“

cell.button.setimage.... 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题