ios 8 Swift – embedded式CollectionView的TableView

我对iOS编程相对比较陌生,并且尝试了一些东西,但无济于事。

我想在一个TableViewCell里面放一个CollectionView 。 我可以单独编码,但不知道如何设置和引用TableViewCell每个CollectionView

我已经find了这个教程, http://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell/它展示了如何在Objective-C中完成,但是我一直在与Obj-C进行斗争。

有谁知道一个Swift教程或可以协助? 我正在创build一个简单的项目/代码,我将尽快发布,以帮助您。

编辑1

我刚刚find了上述链接的快速版本。 我正在通过这个工作,但似乎过于复杂,修改AppDelegate。

https://github.com/DahanHu/DHCollectionTableView

非常感谢Rob

创build一个通常的UITableView并在你的UITableViewCell中创buildUICollectionView。 你的collectionView委托和数据源应该符合那个UITableViewCell。

只要经过这个

在你的ViewController中

 // Global Variable var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: self.view.bounds) tableView.delegate = self tableView.dataSource = self self.view.addSubview(tableView) tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "TableViewCell") tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "NormalCell") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 3 { var cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("TableViewCell", forIndexPath: indexPath) as! TableViewCell cell.backgroundColor = UIColor.groupTableViewBackgroundColor() return cell } else { var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("NormalCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = "cell: \(indexPath.row)" return cell } } 

正如你所看到的,我已经创build了两个不同的单元格,一个自定义的TableViewCell,只有当行索引是3时才返回,而在其他索引中则是基本的UITableViewCell。

自定义“TableViewCell”将有我们的UICollectionView。 所以创build一个UITableViewCell子类并记下下面的代码。

 import UIKit class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate { var collectionView: UICollectionView! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell") collectionView.backgroundColor = UIColor.clearColor() self.addSubview(collectionView) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! UICollectionViewCell if indexPath.row%2 == 0 { cell.backgroundColor = UIColor.redColor() } else { cell.backgroundColor = UIColor.yellowColor() } return cell } } 

希望能帮助到你。

细节

xCode 8.2.1,swift 3

快速启动

视图控制器

 import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.tableFooterView = UIView() } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionViewTableViewCell") as! CollectionViewTableViewCell return cell } } 

CollectionViewTableViewCell

 import UIKit class CollectionViewTableViewCell: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! override func awakeFromNib() { super.awakeFromNib() collectionView.dataSource = self collectionView.delegate = self } } extension CollectionViewTableViewCell: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell cell.label.text = "\(indexPath)" return cell } } extension CollectionViewTableViewCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("collectionViewCell selected \(indexPath)") } } 

CollectionViewCell

 import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var label: UILabel! } 

Main.storyboard

 <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/> <capability name="Constraints to layout margins" minToolsVersion="6.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="Collections" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="200" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="pS5-CW-ipl"> <rect key="frame" x="0.0" y="20" width="375" height="647"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="CollectionViewTableViewCell" id="bMP-Ac-C8D" customClass="CollectionViewTableViewCell" customModule="Collections" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="375" height="200"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bMP-Ac-C8D" id="mcy-FO-bcc"> <rect key="frame" x="0.0" y="0.0" width="375" height="199"/> <autoresizingMask key="autoresizingMask"/> <subviews> <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="yY4-ue-1HX"> <rect key="frame" x="8" y="8" width="359" height="183"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <collectionViewFlowLayout key="collectionViewLayout" scrollDirection="horizontal" minimumLineSpacing="10" minimumInteritemSpacing="10" id="pPl-9q-MGc"> <size key="itemSize" width="192" height="185"/> <size key="headerReferenceSize" width="0.0" height="0.0"/> <size key="footerReferenceSize" width="0.0" height="0.0"/> <inset key="sectionInset" minX="10" minY="0.0" maxX="10" maxY="0.0"/> </collectionViewFlowLayout> <cells> <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="CollectionViewCell" id="g9z-R1-8XJ" customClass="CollectionViewCell" customModule="Collections" customModuleProvider="target"> <rect key="frame" x="10" y="2" width="180" height="180"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center"> <rect key="frame" x="0.0" y="0.0" width="180" height="180"/> <autoresizingMask key="autoresizingMask"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="rHM-Xn-vBW"> <rect key="frame" x="69" y="80" width="42" height="21"/> <fontDescription key="fontDescription" type="system" pointSize="17"/> <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <nil key="highlightedColor"/> </label> </subviews> </view> <color key="backgroundColor" red="0.28627450980000002" green="0.56470588239999997" blue="0.8862745098" alpha="1" colorSpace="calibratedRGB"/> <constraints> <constraint firstItem="rHM-Xn-vBW" firstAttribute="centerX" secondItem="g9z-R1-8XJ" secondAttribute="centerX" id="AXf-f9-ruf"/> <constraint firstItem="rHM-Xn-vBW" firstAttribute="centerY" secondItem="g9z-R1-8XJ" secondAttribute="centerY" id="gw4-Iv-7ML"/> </constraints> <size key="customSize" width="180" height="180"/> <connections> <outlet property="label" destination="rHM-Xn-vBW" id="9SL-Kv-ZtD"/> </connections> </collectionViewCell> </cells> </collectionView> </subviews> <constraints> <constraint firstItem="yY4-ue-1HX" firstAttribute="bottom" secondItem="mcy-FO-bcc" secondAttribute="bottomMargin" id="04L-lF-Idy"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="leading" secondItem="mcy-FO-bcc" secondAttribute="leadingMargin" id="Fjd-8j-qvK"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="trailing" secondItem="mcy-FO-bcc" secondAttribute="trailingMargin" id="PUa-ze-U5s"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="top" secondItem="mcy-FO-bcc" secondAttribute="topMargin" id="XX6-d1-Vgx"/> </constraints> </tableViewCellContentView> <connections> <outlet property="collectionView" destination="yY4-ue-1HX" id="tLL-Om-JIX"/> <outlet property="collectionViewFlowLayout" destination="pPl-9q-MGc" id="Ftw-AT-QvP"/> </connections> </tableViewCell> </prototypes> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="pS5-CW-ipl" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="0gc-Bx-lZk"/> <constraint firstAttribute="trailing" secondItem="pS5-CW-ipl" secondAttribute="trailing" id="E5C-aN-sUJ"/> <constraint firstItem="pS5-CW-ipl" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="NiC-h8-1pm"/> <constraint firstItem="pS5-CW-ipl" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="n9e-UY-rtF"/> </constraints> </view> <connections> <outlet property="tableView" destination="pS5-CW-ipl" id="Gfe-HE-Ub6"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="136.80000000000001" y="137.18140929535232"/> </scene> </scenes> </document> 

结果

在这里输入图像说明

正确的MVC例子

视图控制器

 import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate var tableViewCellCoordinator: [IndexPath: Int] = [:] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() } } // UITableViewDataSource extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 5 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionViewTableViewCell") as! CollectionViewTableViewCell cell.collectionView.delegate = self cell.collectionView.dataSource = self let tag = 10000*(indexPath.section+1)+indexPath.row cell.collectionView.tag = tag tableViewCellCoordinator[indexPath] = tag return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "section: \(section)" } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let cell = cell as! CollectionViewTableViewCell cell.collectionView.reloadData() cell.collectionView.contentOffset = .zero } } // UICollectionViewDataSource extension ViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell return cell } } // UICollectionViewDelegate extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let cell = cell as! CollectionViewCell cell.label.text = "\(tableViewCellCoordinator.key(forValue: collectionView.tag)!) \(indexPath)" } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("selected collectionViewCell with indexPath: \(indexPath) in tableViewCell with indexPath: \(tableViewCellCoordinator.key(forValue: collectionView.tag)!)") } } 

CollectionViewTableViewCell

 import UIKit class CollectionViewTableViewCell: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! } 

CollectionViewCell

 import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var label: UILabel! } 

Main.storyboard

 <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/> <capability name="Constraints to layout margins" minToolsVersion="6.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_31582378" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="200" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="pS5-CW-ipl"> <rect key="frame" x="0.0" y="20" width="375" height="647"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="CollectionViewTableViewCell" id="bMP-Ac-C8D" customClass="CollectionViewTableViewCell" customModule="stackoverflow_31582378" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="375" height="200"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bMP-Ac-C8D" id="mcy-FO-bcc"> <rect key="frame" x="0.0" y="0.0" width="375" height="199"/> <autoresizingMask key="autoresizingMask"/> <subviews> <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="yY4-ue-1HX"> <rect key="frame" x="8" y="8" width="359" height="183"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <collectionViewFlowLayout key="collectionViewLayout" scrollDirection="horizontal" minimumLineSpacing="10" minimumInteritemSpacing="10" id="pPl-9q-MGc"> <size key="itemSize" width="180" height="180"/> <size key="headerReferenceSize" width="0.0" height="0.0"/> <size key="footerReferenceSize" width="0.0" height="0.0"/> <inset key="sectionInset" minX="10" minY="0.0" maxX="10" maxY="0.0"/> </collectionViewFlowLayout> <cells> <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="CollectionViewCell" id="g9z-R1-8XJ" customClass="CollectionViewCell" customModule="stackoverflow_31582378" customModuleProvider="target"> <rect key="frame" x="10" y="2" width="180" height="180"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center"> <rect key="frame" x="0.0" y="0.0" width="180" height="180"/> <autoresizingMask key="autoresizingMask"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="rHM-Xn-vBW"> <rect key="frame" x="69" y="80" width="42" height="21"/> <fontDescription key="fontDescription" type="system" pointSize="17"/> <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <nil key="highlightedColor"/> </label> </subviews> </view> <color key="backgroundColor" red="0.28627450980000002" green="0.56470588239999997" blue="0.8862745098" alpha="1" colorSpace="calibratedRGB"/> <constraints> <constraint firstItem="rHM-Xn-vBW" firstAttribute="centerX" secondItem="g9z-R1-8XJ" secondAttribute="centerX" id="AXf-f9-ruf"/> <constraint firstItem="rHM-Xn-vBW" firstAttribute="centerY" secondItem="g9z-R1-8XJ" secondAttribute="centerY" id="gw4-Iv-7ML"/> </constraints> <size key="customSize" width="180" height="180"/> <connections> <outlet property="label" destination="rHM-Xn-vBW" id="9SL-Kv-ZtD"/> </connections> </collectionViewCell> </cells> </collectionView> </subviews> <constraints> <constraint firstItem="yY4-ue-1HX" firstAttribute="bottom" secondItem="mcy-FO-bcc" secondAttribute="bottomMargin" id="04L-lF-Idy"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="leading" secondItem="mcy-FO-bcc" secondAttribute="leadingMargin" id="Fjd-8j-qvK"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="trailing" secondItem="mcy-FO-bcc" secondAttribute="trailingMargin" id="PUa-ze-U5s"/> <constraint firstItem="yY4-ue-1HX" firstAttribute="top" secondItem="mcy-FO-bcc" secondAttribute="topMargin" id="XX6-d1-Vgx"/> </constraints> </tableViewCellContentView> <connections> <outlet property="collectionView" destination="yY4-ue-1HX" id="tLL-Om-JIX"/> <outlet property="collectionViewFlowLayout" destination="pPl-9q-MGc" id="Ftw-AT-QvP"/> </connections> </tableViewCell> </prototypes> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="pS5-CW-ipl" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="3vT-w2-JGU"/> <constraint firstItem="pS5-CW-ipl" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="eS2-Y5-fxg"/> <constraint firstItem="pS5-CW-ipl" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="hFA-oB-bWJ"/> <constraint firstAttribute="trailing" secondItem="pS5-CW-ipl" secondAttribute="trailing" id="yin-cp-cAP"/> </constraints> </view> <connections> <outlet property="tableView" destination="pS5-CW-ipl" id="Gfe-HE-Ub6"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="136.80000000000001" y="137.18140929535232"/> </scene> </scenes> </document> 

结果

在这里输入图像说明 在这里输入图像说明

想想MVC和embedded永远不会像上面这样编程。 UIView的一个子类( – >多数民众赞成什么一个单元格真的是)从来没有委托类委托和一个tableView的数据源(相同的collectionView)。

你有没有创build一个tableview的子类来完成这个子类中的所有程序化的东西 – 不! 你在你的viewcontroller中做 – 因为你在控制器中创buildUIView,来“控制”它们。 所以你需要做的正确方法是:

让我给你一个例子(在老学校“更好理解”的方式):

  1. 用tableView创build一个ViewController,并将这个collectionView添加(addSubview)到你的UITableViewCell。
  2. 在Storyboard上有一个ViewController,并且embedded了一个UITableView
  3. 它也与你的ViewController类作为Outlet(以及他的委托和数据源)
  4. 而不是现在您的自定义UITableViewCell添加CollectionView,只需添加一个“内容持有人”UIView(与约束)。 稍后,您将使用此视图将collectionview添加为子视图。

  5. 现在用XIB创build一个新的UIViewController(New File> …), 或者从Storyboard的属性面板中拖放一个新的UIViewController,并创build一个UIViewController类。 不要忘记互相连接。 (我们会做第一个更好的理解)

  6. 新的ViewController就像一个具有CollectionView的ViewController一样处理(与1相似,但是collectionView)
  7. 在这个带有collectionView的新ViewController中,你可以像往常一样处理所有的代理和数据源等等。

  8. 现在 :在ViewController(第一个)与tableView你实例化每个单元格(cellForRowAtIndexPath)新的ViewController(与collectionView),并将他的collectionView作为子视图添加到您创build的当前视图(如内容持有人),例如:

让myViewControllerWithCollectionView = MyViewControllerWithCollectionView()myCell.contentHolderView.addSubview(myViewControllerWithCollectionView.collectionView)

你也可以做(也许更新,更好的方法,从来没有尝试过自己,但我相信它会工作得很好,是:UIContainerView)。

而已! 给你一些提示:

  • 在cellForRowAtIndexPath中添加新的子视图时要小心,如果contentHolderView已经有一个

    myViewControllerWithCollectionView.collectionView

从“collectionView”获取“Actions”到您当前的“View”将自定义协议(委托)添加到您的视图以获取更多信息。 切勿将代表和数据源从您的collectionView设置到您的主tableViewController,只要处理右视图控制器上的所有内容,并根据需要将信息推送到任何其他viewcontroller。