i am trying to add a TableView inside UICollectionViewCell, so i want to manage that cell by myself from TableView.
So to be more clear, if indexPath.row is 2, then i want to call my tableView cell's inside collectionview indexPath.row.
Please check the picture, i have made with red colour what i want to do.
I created everything programmatically, using UICollectionViewController and UICollectionViewControllerFlowLayout.
For those who need it, i found the solution:
class CustomizedCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate {
var tableView = UITableView()
let cellIdentifier: String = "tableCell"
override func layoutSubviews() {
super.layoutSubviews()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier)
cell.textLabel?.text = "1 CUP"
cell.detailTextLabel?.text = "Whole"
return cell
}
}
Then at viewDidLoad method at CollectionView i did this:
collectionView?.register(CustomizedCell.self, forCellWithReuseIdentifier: "cell")
And after that i have called like this at cellForRowAt indexPath method of UICollectionView:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomizedCell
return cell
}
You can create a custom UICollectionView cell for that indexpath. And add a tableview in the cell xib.
Implement the delegate methods of tableview in custom cell class.
class CustomCollectionViewCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate
{
#IBOutlet var tableView: UITableView!
override func layoutSubviews()
{
super.layoutSubviews()
tableView.delegate = self
tableView.dataSource = self
}
}
The approaches above don't work well in with the MVC pattern. I recommend creating an NSObject subclass which conforms to UITableViewDelegate and UITableViewDataSource.
For example:
class DataProvider: NSObject, UITableViewDelegate, UITableViewDataSource {
let dataManager = DataManager()
let reuseId = "Cell"
//MARK: - DataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataManager.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath)
cell.backgroundColor = .yellow
return cell
}
//MARK: - Delegate Methods
}
Now in your UICollectionViewCell subclass you can specify the tableView data source and delegate properties, like so:
class ContainerCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var collectionView: UICollectionView!
let dataProvider = DataProvider()
let tableView: UITableView = {
let table = UITableView()
table.translatesAutoresizingMaskIntoConstraints = false
return table
}()
override func awakeFromNib() {
super.awakeFromNib()
addSubview(tableView)
tableView.fillSuperview()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: dataProvider.reuseId)
tableView.delegate = dataProvider
tableView.dataSource = dataProvider
}
}
Perhaps not perfect, but achieves better encapsulation than the above answers.
I found a solution that's working for me.
import UIKit
class FirstCollectionViewCell: UICollectionViewCell {
let cellId = "cellId"
let tableView:UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .blue
addSubview(tableView)
setUpViews()
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":tableView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":tableView]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init is not done")
}
func setUpViews() {
tableView.delegate = self
tableView.dataSource = self
tableView.register(MyCell.self, forCellReuseIdentifier: cellId)
}
}
extension FirstCollectionViewCell: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! MyCell
cell.label.text = "Testing testing"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40.0
}
}
class MyCell:UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// creating a label to display some dummy text
let label:UILabel = {
let label = UILabel()
label.text = "test"
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setUpViews() {
addSubview(label)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
}
}
Related
I have a collection view inside a table view and a button in the collection view cell. I want to push another vc when that button is pressed.
I tried creating a delegate in the collection view cell, but the collection view cell has a cellforitem method in the table cell, so the delegate cannot be declared in the main view controller.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
setUpTableView()
}
func setUpTableView() {
let tableView = UITableView()
view.addSubview(tableView)
tableView.register(
HomeRecommendStoreTableViewCell.self,
forCellReuseIdentifier: HomeRecommendStoreTableViewCell.identifier
)
tableView.register(
UITableViewCell.self,
forCellReuseIdentifier: "cell"
)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .black
tableView.showsVerticalScrollIndicator = false
tableView.separatorStyle = .none
tableView.contentInsetAdjustmentBehavior = .never
self.tableView = tableView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: HomePopularTableViewCell.identifier, for: indexPath) as? HomePopularTableViewCell else { return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)}
cell.selectionStyle = .none
return cell
}
}
class TableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
static let identifier = "HomeRecommendStoreTableViewCell"
private var collectionView: UICollectionView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .black
setUpCollectionView()
}
required init?(coder: NSCoder) {
fatalError()
}
func setUpCollectionView() {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: layout
)
layout.scrollDirection = .horizontal
collectionView.register(
HomeRecommendStoreCollectionViewCell.self,
forCellWithReuseIdentifier: HomeRecommendStoreCollectionViewCell.identifier
)
collectionView.register(
UICollectionViewCell.self,
forCellWithReuseIdentifier: "cell"
)
collectionView.clipsToBounds = false
collectionView.backgroundColor = .black
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
contentView.addSubview(collectionView)
collectionView.snp.makeConstraints { make in
make.top.equalToSuperview().offset(40)
make.leading.equalToSuperview().offset(20)
make.trailing.equalToSuperview()
make.bottom.equalToSuperview().inset(80)
}
self.collectionView = collectionView
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: HomeRecommendStoreCollectionViewCell.identifier, for: indexPath
) as? HomeRecommendStoreCollectionViewCell else {
return collectionView.dequeueReusableCell(
withReuseIdentifier: "cell", for: indexPath
)
}
return cell
}
}
class CollectionViewCell: UICollectionViewCell {
static let identifier = "HomeRecommendStoreCollectionViewCell"
private lazy var listButton: UIButton = {
let button = UIButton()
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
func setUp() {
listButton.addTarget(self, action: #selector(onTap), for: .touchUpInside)
}
#objc func onTap() {
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
First you have to make a property in tableViewCell:
weak var parent:ViewController?
Then in viewController you have to use cell for row of tableView:
cell.parent = self
Then create same property in collectionViewCell:
weak var parent:ViewController?
And use collectionView func cell for item at:
cell.parent = parent
And use that parent inside your button func:
#objc func onTap() {
let destinationVC = NextViewController()
parent?.navigationController.pushViewController(destinationVC,animated:true)
}
Since the delegate is inside the collectionView, you can get a callback in TableView cell and then with another delegate you can get the call back in your ViewController.
Or else you can also use notifications in order to get callbacks.
Or closures can also be used.
This question already has answers here:
TableViewCell is not clickable with one finger tap, but it is with two fingers
(3 answers)
Closed 3 years ago.
I'm not receiving the touches. It shows the selection on the iPhone's screen, but it doesn't performs the method didSelectRow.
usersTV.register(UserCell.self, forCellReuseIdentifier: "userCell")
usersTV.dataSource = self
usersTV.delegate = self
usersTV.backgroundColor = .clear
usersTV.separatorColor = .white
usersTV.translatesAutoresizingMaskIntoConstraints = false
usersTV.isHidden = true
usersTV.tableFooterView = UIView()
usersTV.isUserInteractionEnabled = true
usersTV.isEditing = false
usersTV.allowsSelection = true
usersTV.allowsSelectionDuringEditing = false
usersTV.allowsMultipleSelection = false
usersTV.allowsMultipleSelectionDuringEditing = false
usersTV.delaysContentTouches = false
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
Everything is programatically written.
The cells are custom with 3 labels and added constraints.
What could be the problem ?
UPDATE:
class UserCell : UITableViewCell{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let viewsDict = ["userName":userName,"field1":field1,"field2":field2]
contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[userName(120)]-8-[field1]-8-[field2(120)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[userName]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[field1]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
contentView.superview?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[field2]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
UPDATE:
The didSelectRow method works only if you tap with 2 fingers...
TableViewCell is not clickable with one finger tap, but it is with two fingers
The answer of this question helped me. I've set GestureRecognizer on the main view. When I remove it the problem fixes.
I think this code will help you.If not,There may be a issue with the label constraints.
#IBOutlet weak var UserTV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
UserTV.register(UserCell.self, forCellReuseIdentifier: "userCell")
UserTV.dataSource = self
UserTV.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let vc :UserCell = self.UserTV.dequeueReusableCell(withIdentifier: "userCell") as! UserCell
vc.textLabel?.text = "Index: \(indexPath.row)"
vc.backgroundColor = UIColor.red
return vc
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Slected \(indexPath.row)")
}
First of all, here is my comment on your code:
No need to go much complex for this easy task.
Don't forgot to set delegate and datasource properly.
No need to use Visual Format way to set constraints, use Anchors.
My suggestion for you:
Always try to use UICollectionView instead of UITableView.
class SampleTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Variables
lazy private var listTableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
// MARK: - View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
initialSetup()
}
// MARK: - Private Methods
private func initialSetup() {
view.backgroundColor = .white
view.addSubview(listTableView)
listTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
listTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
listTableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
listTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
listTableView.register(UITableViewCell.self, forCellReuseIdentifier: "listCell")
}
// MARK: - TableView Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
cell.textLabel?.text = "Table Row - \(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
}
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?
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
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.