I want to add a UICollectionView inside a table view cell.For this purpose, i have created below files.
CollectionCell:
class CollectionCell: UICollectionViewCell {
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var imgCell: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
I have also created a CollectionCell.xib
CollectionView.swift
class CollectionView: UIView {
#IBOutlet weak var collectionview: UICollectionView!
var arrItems:[String] = []
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
func configureCollectionView()
{
collectionview.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
collectionview.delegate = self
collectionview.dataSource = self
}
func setCollectionViewDatasource(arrItems:[String])
{
self.arrItems = arrItems
self.collectionview.reloadData()
}
static func initiateView()->CollectionView
{
let nib = UINib(nibName: "CollectionView", bundle: nil)
let view = nib.instantiate(withOwner: nil, options: nil)[0] as! CollectionView
return view
}
}
extension CollectionView:UICollectionViewDelegate
{
}
extension CollectionView:UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:CollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
cell.lblName.text = arrItems[indexPath.row]
return cell
}
}
I have also created CollectionView.xib
Now as i want to add a collectionview inside a tableview cell for that purpose i have created a cutom tableview cell class as CustomTableCell
class CustomTableCell: UITableViewCell {
var view = CollectionView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("ceonstatructir init")
// insitate a nib
view = CollectionView.initiateView()
view.configureCollectionView()
contentView.addSubview(view)
view.setCollectionViewDatasource(arrItems: ["firest","second","thierd"])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setDataSource(arrItems:[String])
{
//view.setCollectionViewDatasource(arrItems: arrItems)
}
}
Now i have created a mainViewController to show the data on tableview so i have crteated viewcontroller.swift
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableview: UITableView!
let sectionArray = ["First","Second","Third","Fourth","Fifth"]
let collectionArray = [["First","Second","Third"],["First","Second","Third"],["First","Second","Third"],["First","Second","Third"],["First","Second","Third"]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableview.register(CustomTableCell.self, forCellReuseIdentifier: "TableCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return sectionArray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionArray[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:CustomTableCell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! CustomTableCell
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell:CustomTableCell = cell as! CustomTableCell
let dataSource = collectionArray[indexPath.section]
cell.setDataSource(arrItems:dataSource)
}
}
Now i am trying to send datasource to my collectionview when tableviewcell is just created.But i am getting crash in cellForItemAtIndexPath in collectionview.I am getting cell as nil in cellForItemAyIndexPath.Please tell me what is the issue with it.
In Collectionview.swift change this function
func configureCollectionView()
{
let nib = UINib(nibName: "CollectionCell", bundle: nil)
collectionview.register(nib, forCellWithReuseIdentifier: "cell")
collectionview.delegate = self
collectionview.dataSource = self
}
In cellforItemat change this line
let cell:CollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
to
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionCell
Related
In myscenario, I am trying to add Dynamic UITableview within Static UITableview Cell. How to achieve this? I tried below code but It is not working for me.
The dynamic tableview cell count based need to readjust static tableview cell height. Please provide some sample code.
Tableview Code
import UIKit
class CustomCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {
var dataArr:[String] = []
var subMenuTable:UITableView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style , reuseIdentifier: reuseIdentifier)
setUpTable()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
setUpTable()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setUpTable()
}
func setUpTable(){
subMenuTable = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain)
subMenuTable?.delegate = self
subMenuTable?.dataSource = self
self.addSubview(subMenuTable!)
}
override func layoutSubviews() {
super.layoutSubviews()
subMenuTable?.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellID")
}
cell?.textLabel?.text = dataArr[indexPath.row]
return cell!
}
}
Create a single view project add tableview inside storyboard and set up its datasource and delegate
do code as below to firstViewController.swift
import UIKit
class firstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? CustomCell
if cell == nil {
cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
cell?.dataArr = ["subMenu->1","subMenu->2","subMenu->3","subMenu->4","subMenu->5"]
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 150.0
}
}
create a new file CustomCell.swift which is the subclass of UITableViewCell and do not select with xib this file is without .xib file table and its cell will be created programatically.
do code as below to CustomCell.swift
import UIKit
class CustomCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {
var dataArr:[String] = []
var subMenuTable:UITableView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style , reuseIdentifier: reuseIdentifier)
setUpTable()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
setUpTable()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setUpTable()
}
func setUpTable(){
subMenuTable = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain)
subMenuTable?.delegate = self
subMenuTable?.dataSource = self
self.addSubview(subMenuTable!)
}
override func layoutSubviews() {
super.layoutSubviews()
subMenuTable?.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellID")
}
cell?.textLabel?.text = dataArr[indexPath.row]
return cell!
}
}
I hope it will work for you ...:)
Do this in your main controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView = self.tableView {
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? CustomCell
cell.tableView.delegate = self
cell.tableView.dataSource = self
return cell!
} else {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")//here you custom cell's tableView's cell
return cell
}
}
Basically you will have to calculate height of your child tableview as demonstrated below
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
#IBOutlet weak var parentTableView : UITableView? = nil
var sections = [[String:[[String:String]]]]()
override func viewDidLoad()
{
super.viewDidLoad()
setup()
}
func setup()
{
// Data
let section1 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"]]]
let section2 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"], ["Title" : "Row 3"]]]
let section3 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"], ["Title" : "Row 3"], ["Title" : "Row 4"]]]
sections.append(section1)
sections.append(section2)
sections.append(section3)
// Register header
}
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return sections.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
// Calculate the height of parent cell.
var cellHeight : CGFloat = 0.0
let aSection = sections[indexPath.row]
if let items = aSection["Items"]
{
cellHeight = CGFloat(44 * items.count)
}
return cellHeight
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if let cell = tableView.dequeueReusableCell(withIdentifier: "ParentTableViewCell") as? ParentTableViewCell
{
if let aSection = sections[indexPath.row] as? [String:[[String:String]]], let items = aSection["Items"]
{
cell.configure(items: items)
}
return cell
}
return UITableViewCell()
}
}
Here is the link for the code
I have 2 xib files: the custom UIView and the Custom Cell xib.
I also have a Custom Cell class that only contains a UILabel.
The names are all correct.
The delegates of the UITableView are connected to the view.
I need to add a UITableView to a UIView. From the tutorials I've read this is how to add it. But for some reason this does not work I get 2 types of errors with this code that say that I need to register the cell nib or that It finds nil when unwrapping an optional. What am I doing wrong? Please help!
private let myArray: NSArray = ["First","Second","Third"]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
#IBOutlet var contentView: UIView!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var HelperLabel: UILabel!
override init(frame: CGRect){
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit(){
let nib = UINib(nibName: "MyCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "MyCell")
tableView.dataSource = self
tableView.delegate = self
self.addSubview(tableView)
Here is the complete Code for your Problem
Code For CustomCell Class : Take Custom Xib For Cell
import UIKit
class CustomCell: UITableViewCell {
#IBOutlet weak var myLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Code For CustomView Class: Take Custom Xib For View
import UIKit
class CustomView: UIView {
var tableData: [String] = ["First","Second","Third"]
#IBOutlet weak var myTableView: UITableView!
class func instanceFromNib() -> UIView {
return UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
static func nibInstance() -> CustomView? {
let customView = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil).first as? CustomView
return customView
}
func baseInit() {
self.myTableView.delegate = self
self.myTableView.dataSource = self
self.myTableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
}
}
extension CustomView : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.myLabel.text = tableData[indexPath.row]
return cell
}
}
Note : Set the Xib CustomClass to UIView Class whatever you want to take in my case it is "CustomView"
Controller Code :
class CustomViewController: UIViewController {
var customView : CustomView?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(0.5))) {
self.loadViewCustom()
}
}
func loadViewCustom() {
self.customView = CustomView.nibInstance()
self.customView?.frame = self.view.frame
self.customView?.baseInit()
self.view.addSubview(self.customView!)
self.customView?.myTableView.reloadData()
}
}
tableView is IBOutlet in xib file? why you need addSubView?
The above one is my inner cell. I want to load this cell inside the below cell. The number of inner cell is dynamic.
The above one is my main cell. The red colored section is a UIView. I want to add numbers of innerCell dynamically into the UIView. I tried the below code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mainCell = tableView.dequeueReusableCell(withIdentifier: "FlightCellMain", for: indexPath) as? FlightCellMain
let innerCell = tableView.dequeueReusableCell(withIdentifier: "FlightCell", for: indexPath) as? FlightCell
mainCell?.flightCellView.addSubview(innerCell!)
mainCell?.backgroundColor = .clear
innerCell?.backgroundColor = .clear
// innerCell?.innerCellWidthConst.constant = (mainCell?.mainView.frame.width)!
self.showStopsView(2, self.airportlist, (innerCell?.leftRound)!, (innerCell?.rightRound)!, (innerCell?.centerLine)!, (innerCell?.routeView)!)
mainCell?.flightCellViewHieghtConst.constant = (mainCell?.flightCellViewHieghtConst.constant)! + 125
innerCell?.layoutIfNeeded()
mainCell?.layoutIfNeeded()
return mainCell!
}
But the result is getting like this. I provided autolayout. When I run the two cells individually it fits its content.. Whats wrong am I doing ?
The above picture is the model that I'm trying to achieve. Where the number of flights details is dynamic.
Step 1: Create a FlightDisplayView(UIView).
import UIKit
class FlightDisplayView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit (){
let xibs = Bundle.main.loadNibNamed("FlightDisplayView", owner: self, options: nil)
let view = xibs?.first as! UIView
view.frame = self.bounds;
self.addSubview(view)
}
}
Step 2: Create a FlightDisplayCell(UITableViewCell).
import UIKit
class FlightViewCell: UITableViewCell {
#IBOutlet weak var innerCellView:FlightDisplayView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Step 3: Create a mainCell(UITableViewCell).
import UIKit
class mainCell: UITableViewCell {
#IBOutlet weak var table: UITableView!
#IBOutlet var heightConstraintForFlightTableView : NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
table.delegate = self
table.dataSource = self
table.estimatedRowHeight = 100.0
table.rowHeight = UITableViewAutomaticDimension
table.register(UINib.init(nibName: "FlightViewCell", bundle: nil), forCellReuseIdentifier: "FlightViewCell")
heightConstraintForFlightTableView.constant = 0.0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setInformation(_ numberOFFlight : CGFloat, _ information : NSDictionary) {
heightConstraintForFlightTableView.constant = numberOFFlight * 155.0
// 155 is fixed flight cell height
table.reloadData()
}
}
extension mainCell:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FlightViewCell")
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
}
Step 4: Use mainCell into your controller. (3 cell information added as a inner cell)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell") as? mainCell
let information:NSDictionary = [:]
cell?.setInformation(3, information)
return cell!
}
I have made a CollectionView in a TableView for vertical and horizontal scrolling and customisable cells. This works so far. The problem is: I can't select an item of the CollectionView. I think the problem could be something with the delegate outlets but I could't find a solution.
I'm pretty new with Swift, so maybe I overlook something obvious.
My TableViewController:
import UIKit
class HomeVTwoTableViewController: UITableViewController {
var headers = ["Live", "Friends", "Last commented"]
#IBAction func cancelBtnPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.black
let header = view as! UITableViewHeaderFooterView
if section == 0 {
header.textLabel?.textColor = UIColor.black
view.tintColor = UIColor.white
}
else {
view.tintColor = UIColor.groupTableViewBackground
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return headers.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellBig", for: indexPath) as! HomeVTwoTableViewCell
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 225.0
}
else {
return 120.0
}
}
}
My TableViewCell with the CollectionView:
import UIKit
class HomeVTwoTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var collectionView: UICollectionView!
fileprivate var images = [UIImage]()
{
didSet
{
self.collectionView.reloadData()
}
}
func setup(for images: [UIImage])
{
self.images = images
}
override func layoutSubviews() {
collectionView.dataSource = self
}
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return communityName.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return communityName.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("didSelect")
selectedCommunity = communityId[indexPath.row]
let home = HomeViewController()
home.showCommunityDetail()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellBig", for: indexPath) as? HomeVTwoCollectionViewCell else
{
fatalError("Cell has wrong type")
}
//cell.imageView.image = image
cell.titleLbl.text = communityName[indexPath.row]
cell.imageView.downloadedFrom(link :"deleted because privat")
return cell
}
}
My CollectionViewCell:
import UIKit
class HomeVTwoCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var titleLbl: UILabel!
}
You need to set delegate and dataSource like this
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.dataSource = self
collectionView.delegate = self
}
I think you missed this line. Just add, it will work fine collectionView.delegate = self
You have not confirm delegate of collection view.
override func layoutSubviews() {
collectionView.dataSource = self
collectionView.delegate = self
}
import UIKit
class NewOrdersViewControllers: UIViewController,UITableViewDelegate,UITableViewDataSource {
var items = ["Chilli and Lemon"]
#IBOutlet var tableView:UITableView!
#IBOutlet weak var lblRestaurantNames: UILabel!
#IBOutlet weak var mapView: UIButton!
var cellIdentifier = "cell"
init() {
super.init(nibName : "NewOrdersViewControllers", bundle:nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "tableCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: cellIdentifier)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
#IBAction func mapPush(sender: AnyObject) {
let mapVC = MapViewController()
self.navigationController?.pushViewController(mapVC, animated: true)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:tableCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! tableCell
//cell.textLabel?.text = self.items[indexPath.row] as! String
cell.RestaurantLbl.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
I have done it using xib and it shows the following error.
Could not cast value of type 'UITableViewCell' (0x1fe82bc)
In your viewDidLoad() method you register 2 different cell types for the same reuseIdentifier, so the last one (UITableViewCell) takes effect. That's why in tableView:cellForRowAtIndexPath: the cells being dequeued are also of UITableViewCell class and may not be cast to your custom cell class.
Try to remove the line:
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
it should fix your problem and let the tableView dequeue the correct cells.