2016-07-17 2 views
0

Я новичок в программировании Swift Ios.
Прежде всего, извиняюсь, потому что мое английское письмо плохое.
Я хочу установить DataSource & Делегат UICollectionView из другого класса Swift, но мои функции класса Swift не звонят, и мой CollectionView ничего не показывает.
Если мой DataSource & Делегат установлен в Self, все работает хорошо.
Мой класс DataSource является:
LivePlayListAdapter.swift
Swift UICollectionView не устанавливает DataSource & Delegate программно

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!") 
     } 

    } 
} 

ответ

2

Вы создаете новый экземпляр LivePlayController Thats, почему dataSource и delegate не создаются.

Создание нового экземпляра здесь

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 

    } 
} 
+0

Спасибо, мой Datasource не в этом Vie Класс wController. прочитайте мой код полностью и ответьте мне. –

+0

Почему бы не создать его в контроллере view, в котором он используется? или создать статический func внутри структуры и использовать возвращаемое значение из этого? (Ответ обновлен) – kye

Смежные вопросы