Ios 在TableViewCell中包含图像的CollectionView

Ios 在TableViewCell中包含图像的CollectionView,ios,uitableview,swift3,uicollectionview,Ios,Uitableview,Swift3,Uicollectionview,我想要一个带有5个集合视图的TableView。集合视图必须显示水平滚动的图像。我遵循了本教程: 但我希望图像在我的CollectionView中滚动。我不知道怎么做 以下是我的示例代码: import UIKit class ViewController1: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegateFlowLayout { @IBOut

我想要一个带有5个集合视图的TableView。集合视图必须显示水平滚动的图像。我遵循了本教程:

但我希望图像在我的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 }
   }
}
导入UIKit
类ViewController1:UIViewController、UITableViewDataSource、UITableViewDelegate、UICollectionViewDelegateFlowLayout{
@IBVAR表格视图:UITableView!
var images=[UIImage(名为:“banner2”)、UIImage(名为:“banner1”)、UIImage(名为:“banner3”)、UIImage(名为:“banner4”)、UIImage(名为:“banner5”)]
var storedOffsets=[Int:CGFloat]()
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回5
} 
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
让cell=tableView.dequeueReusableCell(标识符为:“cell2”,用于:indexPath)作为!cell2
cell.frame=CGRect(x:0,y:28,宽度:375,高度:202)
cell.myCollection.reloadData()
返回单元
}
func tableView(tableView:UITableView,willDisplay单元格:UITableView单元格,forRowAt indexath:indexath){
guard let tableViewCell=单元格为?Cell2 else{return}
tableViewCell.setCollectionViewDataSourceDelegate(self,forRow:indexPath.row)
tableViewCell.collectionViewOffset=StoredOffset[indexPath.row]??0
}
func tableView(tableView:UITableView,diEndDisplaying单元格:UITableView单元格,forRowAt indexPath:indexPath){
guard let tableViewCell=单元格为?Cell2 else{return}
storedOffsets[indexPath.row]=tableViewCell.collectionViewOffset
}
}
扩展ViewController1:UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int{
返回图像数
}
func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
让cell=collectionView.dequeueReusableCell(带有reuseidentifier:“cell1”,for:indexPath)作为!cell1
cell.image.image=images[(indepath作为nsindepath.row]
返回单元
}
func collectionView(collectionView:UICollectionView,didSelectItemAt indexPath:indexPath){
打印(“行\(collectionView.tag)处的集合视图所选索引路径\(indexPath)”)
}
}
导入UIKit
类别Cell1:UICollectionViewCell{
@IBVAR图像:UIImageView!
重写初始化(帧:CGRect){
super.init(frame:frame)
image.frame=CGRect(x:0,y:0,宽度:175,高度:175)//这里我得到了exc\u bad\u指令(code=exc\u i386\u invop subcode=0x0)警告
contentView.backgroundColor=UIColor.green
self.contentView.addSubview(图像)
}
必需的初始化?(编码器aDecoder:NSCoder){
super.init(编码者:aDecoder)
}
}
导入UIKit
类别Cell2:UITableViewCell{
@IBMCollection:UICollectionView!
重写func awakeFromNib(){
myCollection.frame=CGRect(x:0,y:28,宽度:375,高度:202)
}
}
扩展单元2{
func setCollectionViewDataSourceDelegate(dataSourceDelegate:D,forRow row:Int){
self.myCollection.delegate=dataSourceDelegate
self.myCollection.dataSource=dataSourceDelegate
myCollection.tag=行
myCollection.setContentOffset(myCollection.contentOffset,动画:false)//如果正在滚动,则停止集合视图。
let layout=UICollectionViewFlowLayout.init()
layout.scrollDirection=.horizontal
layout.sectionInset=UIEdgeInSet(顶部:5,左侧:0,底部:5,右侧:0)
layout.minimumInteritemSpacing=0
layout.minimumLineSpacing=0
layout.itemSize=CGSize(宽:182,高:182)
myCollection=UICollectionView.init(框架:myCollection.frame,collectionViewLayout:layout)
myCollection.register(Cell1.self,强制使用重用标识符:“Cell1”)
self.contentView.addSubview(myCollection)
myCollection.reloadData()
}
var collectionViewOffset:CGFloat{
设置{myCollection.contentOffset.x=newValue}
获取{return myCollection.contentOffset.x}
}
}

粉红色的TableView(我设置了颜色)和黑色的CollectionView(同样,我设置了颜色)我无法查看我的图像或我设置为绿色的CollectionViewCells。当触摸粉红色部分或尝试滚动时,我会得到错误:致命错误:在使用警告-exc\U bad\U指令(code=exc\U i386\U invop subcode=0x0)展开可选值时意外发现nil

有人能告诉我怎么做吗?提前谢谢


我使用的是Xcode 8和Swift 3。

我在OBJECTIVE-C中有一段代码,我认为您必须转换成Swift 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];
 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;
 }
和集合视图cellForItemAtIndexPath

 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];
 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;
 }

我在OBJECTIVE-C中有一段代码,我认为您必须转换成swift 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];
 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;
 }
和集合视图cellForItemAtIndexPath

 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];
 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;
 }

您需要用
UITableViewCell
而不是
ViewController1
实现
UICollectionViewDataSorce
和委托方法。是的,我试过这么做。它为我提供了实现
UICollectionViewDataSorce
和使用
UITableViewCell
而不是
Vi委托方法所需的相同输出