ios - Swift UICollectionView 不以编程方式设置数据源和委托(delegate)

标签 ios swift2 uicollectionview

我是 Swift Ios 编程的新手。
首先,我很抱歉,因为我的英文写作很糟糕。
我想从另一个 Swift 类设置 UICollectionView 的数据源和委托(delegate),但是我的 Swift 类函数没有调用,我的 CollectionView 没有显示任何东西。
如果我的 DataSource & Delegate 设置为 Self 一切正常。
我的数据源类是:
LivePlayListAdapter.swift

import UIKit

class LivePlayListAdapter:UIViewController, UICollectionViewDataSource,UICollectionViewDelegate {


    let numberOfCol:CGFloat = 2
    let reuseIdentifier = "cell"

    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]



    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count

    }

    // make a cell for each cell index path
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell


        cell.labelText = items[indexPath.row]



        return cell
    }

    // MARK: - UICollectionViewDelegate protocol

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
            return CGSize()
        }

        let widthAvailbleForAllItems =  (collectionView.frame.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right)

        let widthForOneItem = widthAvailbleForAllItems / numberOfCol - flowLayout.minimumInteritemSpacing
        return CGSize(width: CGFloat(widthForOneItem), height: CGFloat(widthForOneItem))
    }
}


这是我的 ViewController 类:
LivePlayController.swift 导入 UIKit

class LivePlayController: UIViewController {

    var heyatPlayGridView : UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
       self.heyatPlayGridView = createCollectionView()
        self.view.addSubview(self.heyatPlayGridView)
        self.heyatPlayGridView.reloadData()
        self.heyatPlayGridView.reloadInputViews()
    }

 func createCollectionView() -> UICollectionView{

        let collectionView : UICollectionView!
        let width = UIScreen.mainScreen().bounds.size.width - 6
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
        layout.itemSize = CGSizeMake(width/3, width/3)
        layout.minimumInteritemSpacing = 3
        layout.minimumLineSpacing = 3

        collectionView = UICollectionView(frame:  CGRectMake(10, 110, 300, 400), collectionViewLayout: layout)
        let lid = LivePlayListAdapter()
        collectionView.dataSource = lid
        collectionView.delegate = lid
        collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = UIColor.blueColor()


        return collectionView
    }
}


还有我的 CustomCell 类:
MyCollectionViewCell.swift

import UIKit

class MyCollectionViewCell: UICollectionViewCell {
  let pictureSize = 90;
    let marginTop = 20
    var imageUrl: String = "nature_pic_2"
    var labelText : String = "ss"

    override init(frame: CGRect) {
        var a:CGFloat = CGFloat((frame.width-CGFloat(self.pictureSize))/2)
        if (a<0){
            a=1
        }
        let imageView = UIImageView(frame: CGRectMake(a,CGFloat(marginTop), CGFloat(self.pictureSize), CGFloat(self.pictureSize)));
        let label = UILabel(frame: CGRectMake(0, CGFloat(frame.width-40) , CGFloat(frame.width), CGFloat(30)));
        super.init(frame: frame)


          removeView();
        // set as you want
        let image = UIImage(named: imageUrl);
        imageView.image = image;
        imageView.layer.cornerRadius  = CGFloat(CGFloat(pictureSize)/2.0)
        imageView.layer.masksToBounds = true
        imageView.layer.borderColor = UIColor.whiteColor().CGColor
        imageView.layer.borderWidth = 1
        imageView.tag = 101
        self.addSubview(imageView);


        label.text = labelText;
        label.textColor = UIColor.whiteColor()
        label.font = UIFont(name: Fonts.FarsiFont, size: 23)
        label.textAlignment = NSTextAlignment.Center
        //        label.backgroundColor = UIColor.purpleColor()
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.numberOfLines = 0
        label.tag = 100
        //        label.sizeToFit()
        self.addSubview(label);

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func removeView() {
        if let viewWithTag = self.viewWithTag(100) {
            print("added")
            viewWithTag.removeFromSuperview()
        }else{
            print("No!")
        }

        if let viewWithTag = self.viewWithTag(101) {
            print("added")
            viewWithTag.removeFromSuperview()
        }else{
            print("No!")
        }

    }
}

最佳答案

您正在创建 LivePlayController 的新实例,这就是未设置 dataSourcedelegate 的原因。

在这里创建新实例

 let lid = LivePlayListAdapter()
collectionView.dataSource = lid
collectionView.delegate = lid

更改为

collectionView.dataSource = self
collectionView.delegate = self

更新

struct UICreator{
  static func createCollectionView() -> UICollectionView{

    let collectionView : UICollectionView!
    let width = UIScreen.mainScreen().bounds.size.width - 6
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
    layout.itemSize = CGSizeMake(width/3, width/3)
    layout.minimumInteritemSpacing = 3
    layout.minimumLineSpacing = 3

    collectionView = UICollectionView(frame:  CGRectMake(10, 110, 300, 400), collectionViewLayout: layout)
//    collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    collectionView.backgroundColor = UIColor.blueColor()

    return collectionView
  }
}


class ExampleVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{

  var myCollectionView: UICollectionView!

  override func viewDidLoad() {
    myCollectionView = UICreator.createCollectionView()
    myCollectionView.delegate = self
    myCollectionView.dataSource = self

  }
}

关于ios - Swift UICollectionView 不以编程方式设置数据源和委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422480/

相关文章:

ios - Swift - 无法显示导航栏

ios - 具有环绕但不滚动的 UIView 的水平列表

swift2 - 如何使用 Alamofire 获取 Twitter 访问 token (Swift 2.2)

ios - Swift,无法读取url中的数据

ios - 扩展保存特定元素类型的快速数组

ios - 为什么我的 UICollectionView 单元格在我的 swift ios 应用程序中不可点击?

ios - 为什么我的 collectionViewCell 显示异常行为?

ios - 段错误 11 - 桥接头

ios - Swift:UnsafeMutablePointer.deinitialize 追加到数组时出现负计数的 fatal error

单击完成按钮时,带有 YouTube 视频的 iOS UIWebView 不会关闭