2016-05-08 5 views
1

私はcollectionViewsTableViewsを使って作業していますが、これはちょっと混乱します。私はコレクションビューをViewControllerと一緒にデリゲートとデータソース自身にセットしています。しかし、didSelectItemAtIndexPathを使用しようとすると、何も起こりません。コレクションも完全に表示され、データソース関数がうまく機能しています。コレクションビューSwiftでアイテムを選択できません

これは私のコードです:

@IBOutlet weak var timeCollectionView: UICollectionView! 

override func viewDidLoad() { 
     super.viewDidLoad() 

     //Register the Cell 
     let nib = UINib(nibName: "DurationSelectionCollectionViewCell", bundle:nil) 
     self.timeCollectionView.registerNib(nib, forCellWithReuseIdentifier: "DurationSelectionCollectionViewCell") 

     timeCollectionView.delegate = self 
     timeCollectionView.dataSource = self 

     .... 

} 

//Selecting an item and highlighting it. 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     timeCollectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.grayColor() 

} 

答えて

0

あなたはコレクションビュー内の項目を選択する上で、背景色を変更したい場合は、あなたがあなたのUICollectionViewCellをサブクラス化しhighlightedプロパティをオーバーライドする必要があります。

class DurationSelectionCollectionViewCell: UICollectionViewCell { 
    override var highlighted: Bool { 
     didSet { 
      contentView.backgroundColor = highlighted ? .grayColor() : nil 
     } 
    } 
} 
+0

私はそれを試しただけで何も起こっていません! didSelectItemAtIndexPathItemにブレークポイントの場所があり、セルのいずれかをクリックすると、関数がコールを受け取ったことを示すフィードバックが表示されません。 – Gugulethu

1

私はこれをテストしましたが、コレクションビューのデリゲートとデータソースが接続されている限り動作しました。あなたの問題は、didSelectItemAtIndexPath宣言であなたに与えられた汎用のcollectionView変数を呼び出すtimeCollectionViewを呼び出すことです。私は、以下の太字でそれを強調した:

FUNCのcollectionView(collectionView:UICollectionView、didSelectItemAtIndexPath indexPath:NSIndexPath)

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCustomCollectionViewCell 
    cell.backgroundColor = UIColor.grayColor() 

} 
+0

どちらかわかりませんが、コレクションビューには使用できないと思います。 – Gugulethu

+0

私の謝罪、私は別の答えを加えるつもりです、何が間違っているか考えているかもしれません。 – user3353890

+0

@Gugulethuは私が提供した更新されたソリューションをチェックします。私はXcodeでそれをテストしたので、うまくいくはずです。 – user3353890

0

didSelectItemAtIndexPathItem:が呼び出されない場合は、必ずあなたが適切にdelegatedataSourceを設定している作りますビューコントローラ。

関連する問題