2016-08-19 15 views
2

プログラムでUICollectionViewを作成しましたが、この場合はdidSelectItemAtIndexPathメソッドが呼び出されません。なぜUICollectionView didSelectメソッドが機能しないのですか?

let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: 360), collectionViewLayout: layout) 
collectionView.delegate = self 
collectionView.dataSource = self 
collectionView.userInteractionEnabled = true 

問題は何ですか?私がセルをタップすると、私は自分の反応を得られないのですか?

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    print("Selected Cell: \(indexPath.row)") 
} 
+0

delegateオブジェクトが 'nil'ではないのですか? –

+0

1) 'UICollectionView'と' UICollectionViewCell'の 'Background Color'を設定してみてください。画面上に正しく表示されているかどうかを確認してください。 2) 'UICollectionView'に' userInteractionEnabled' = trueを設定してください – pkc456

+0

@ pkc456なぜですか?すでにセルが表示されており、すでにuserInteractionを有効にしています – Doe

答えて

0

Project NavigatorでViewController.swiftを選択します。

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource 


//After class declaration create a new variable: 

var collectionView: UICollectionView! 



    override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10) 
    layout.itemSize = CGSize(width: 90, height: 120) 

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) 
    collectionView.dataSource = self 
    collectionView.delegate = self 
    collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") 
    collectionView.backgroundColor = UIColor.whiteColor() 
    self.view.addSubview(collectionView) 
} 



func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    print("Selected Cell: \(indexPath.row)") 
} 
関連する問題