2017-02-17 4 views
1

Я хочу, чтобы TableView с 5 CollectionViews один за другим. В представлениях коллекции должны отображаться изображения, которые прокручиваются по горизонтали. Я следовал этому руководству: https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/CollectionView с изображениями внутри TableViewCell

Но я хочу, чтобы изображения прокручивались в моем CollectionView. Я не знаю, как это сделать.

Вот мой пример кода:

import UIKit 

    class ViewController1: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegateFlowLayout { 

    @IBOutlet var tableView: UITableView! 

    var images = [UIImage(named:"banner2"),UIImage(named:"banner1"),UIImage(named:"banner3"),UIImage(named:"banner4"),UIImage(named:"banner5")] 

    var storedOffsets = [Int: CGFloat]() 

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
      return 5 
     } 

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2 
      cell.frame = CGRect(x: 0, y: 28, width: 375, height: 202) 
      cell.myCollection.reloadData() 
      return cell 
     } 

     func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
       guard let tableViewCell = cell as? Cell2 else { return } 
       tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row) 
       tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0 
      } 

     func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
      guard let tableViewCell = cell as? Cell2 else { return } 
      storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset 
     } 
    } 

extension ViewController1: UICollectionViewDelegate, UICollectionViewDataSource { 

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
      return images.count 
     } 

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! Cell1 
      cell.image.image = images[(indexPath as NSIndexPath).row]  
      return cell 
     } 

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
      print("Collection view at row \(collectionView.tag) selected index path \(indexPath)") 
     } 
    } 


import UIKit 
class Cell1: UICollectionViewCell { 

     @IBOutlet var image: UIImageView! 

     override init(frame: CGRect) { 
      super.init(frame: frame) 
       image.frame = CGRect(x: 0, y: 0, width: 175, height: 175) // Here I get exc_bad_instruction (code=exc_i386_invop subcode=0x0) warning 
       contentView.backgroundColor = UIColor.green 
      self.contentView.addSubview(image) 
     } 

     required init?(coder aDecoder: NSCoder) { 
      super.init(coder: aDecoder) 
     } 
    } 

import UIKit 

class Cell2: UITableViewCell { 

     @IBOutlet var myCollection: UICollectionView! 

     override func awakeFromNib() { 
      myCollection.frame = CGRect(x: 0, y: 28, width: 375, height: 202) 
     } 
    } 

extension Cell2 { 

      func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) { 

       self.myCollection.delegate = dataSourceDelegate 
       self.myCollection.dataSource = dataSourceDelegate 
       myCollection.tag = row 
       myCollection.setContentOffset(myCollection.contentOffset, animated:false) // Stops collection view if it was scrolling. 
        let layout = UICollectionViewFlowLayout.init() 
        layout.scrollDirection = .horizontal 
        layout.sectionInset = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0) 
        layout.minimumInteritemSpacing = 0 
        layout.minimumLineSpacing = 0 
        layout.itemSize = CGSize(width: 182, height: 182) 
        myCollection = UICollectionView.init(frame: myCollection.frame, collectionViewLayout: layout) 
        myCollection.register(Cell1.self, forCellWithReuseIdentifier: "cell1") 
        self.contentView.addSubview(myCollection) 
       myCollection.reloadData() 
      } 

var collectionViewOffset: CGFloat { 
    set { myCollection.contentOffset.x = newValue } 
    get { return myCollection.contentOffset.x } 
    } 
} 

My output is like this

Розовый TableView (я установить цвет) и черный CollectionView (Опять же, я поставил цвет) я не могу просмотреть мои изображения или мой CollectionViewCells, который я установил как greenColor. И когда касание в розовой части или попробуйте прокрутить я получаю ошибку: фатальная ошибка: неожиданно обнаружил ноль во время разворачивания необязательное значение с предупреждением - exc_bad_instruction (код = exc_i386_invop субкодовое = 0х0)

Может кто-то сказать как я могу это сделать? Заранее спасибо

Я использую Xcode 8 и Swift 3.

+0

Вы должны реализовать 'UICollectionViewDataSorce' и делегат метода с' UITableViewCell' не с 'ViewController1'. –

+0

Да, я пытался это сделать. Он дает мне тот же результат –

ответ

0

Я фрагмент кода в C объективно-, я думаю, вы должны преобразовать в стремительной 3.0

Вот мой код

Вы можете попробуйте

TableCell cellForRowAtIndexPath

static NSString *CellIdentifier = @"cell3"; 
     CollectionViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[CollectionViewTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     } 
     cell.headerLabel.text = @"DISH TYPE"; 

     cell.collectionView.delegate = self; 
     cell.collectionView.dataSource = self; 
     cell.collectionView.tag = indexPath.row; 
     [cell.collectionView reloadData]; 

и вид коллекции cellForItemAtIndexPath

if(collectionView.tag == 4){ 
     FIPhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"foodTagCell" forIndexPath:indexPath]; 
     NSDictionary *dic = [arrAmenities objectAtIndex:indexPath.row]; 

     NSMutableDictionary *dic1 = [selectedAmenities objectAtIndex:indexPath.row]; 


      NSURL *url = [NSURL URLWithString:[dic valueForKey:@"ImageURL"]]; 
      [cell.photoImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@""]]; 


     return cell; 
} 
+0

Должен ли я добавить код для TableCell cellForRowAtIndexPath в мой ViewController и CollectionCell cellForItemAtIndexPath в классе TableViewCell? Потому что, как вы видите, у меня есть метод CellView cellForItemAtIndexPath в моем внешнем ViewController, и когда я добавляю туда, он показывает ---- if (myCollection.tag == 0) неразрешенное использование идентификатора 'myCollection' --- Не могли бы вы объяснить? –

+0

@AraRose: Вы можете попробовать эту замену myCollection с помощью коллекцииView. –

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