How to subclass custom Cell class with xib in swift - ios

I got stuck with simple issue and can't find any solution.
MyCell.xib has fileowner MyCell : UITableViewCell class.
I use it like that:
viewDidLoad method:
let nib = UINib(nibName: "MyCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "myIdentifier")
tableView cellForRowAt method:
let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier", for: indexPath) as? MyCell
It works good.
I subclass my class to add some new methods:
class SuperCell : MyCell {
func coolMethod {
print("cool")
}
}
And try to use it like that:
let cell = tableView.dequeueReusableCell(withIdentifier: "myIdentifier", for: indexPath) as? SuperCell
it returns nil
How can I make it work?
I tried to create prototype cell in InterfaceBuilder with identifier myIdentifier and with class SuperCell, but it didn't help.
Why do I need it
I just want to use the same view (xib) for different cell classes.
In my case I have common cell (MyCell) with view (xib). MyCell completely describes fields (IBOutlets). Also I want to create some another cell classes that subclasses MyCell, but they will provide some behaviour of these IBOutlets. For example FirstMyCell : MyCell will have method setFieldsFrom(objectOne: ObjectOne) and SecondMyCell : MyCell will have another method setFieldsFrom(anotherObject: ObjectAnother).
Of course, I can just add this two methods into my MyCell class, but it will be unclean.

Do not set the files owner (remove it)
Make sure your your XIBs Custom Class is set to SuperCell:

Related

How do I add custom cells for a tableView which has been added on top of a UIViewController?

I have used a tableView (myTableView) on a usual UIViewController class. I wish to use reusable cells in this tableView to save memory. I did not create separate XIB and dragged and dropped a tableView component on to the viewController.
The cells have been created with a new class HistoryTableViewCell of type UITableViewCell and this class also has an XIB.
I have also created a tableViewCell and its XIB and used the following code in the tableView(_,cellForRowAt:) method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "historyReuseIdentifier", for: indexPath) as! HistoryTableViewCell
cell.meetingDateLabel.text = historyArray![indexPath.section]
return cell
}
This line of code works fine with a tableViewController when I add the following line in the viewDidLoad() method:
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
But the tableView.register property cannot be used with a tableView. How do I make use of the reusable cells here?
Lets say your xib is ok, everything works fine and the only thing left is to register the nib.
First declare your table view:
#IBOutlet weak var tableView: UITableView!
In the viewDidLoad() :
tableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil) , forCellReuseIdentifier: "historyReuseIdentifier")
Also check your tableView's dataSource and delegate.
The answer was actually quite simple. I figured it out after reading a few of the other answers.
All I needed was to replace this line:
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
with this one:
UITableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
Since there is no table view by the name tableView, you need to access the UITableView class.
Do you want to reuse the cells thats ok, to use them you need to register it first..suppose you have multiple tableView in a single ViewController, then you have to register each cell with respective tableView.
just register the tableViewCell with respective tableView and use its reusableIdentifier which you have used while registering the tabelViewcell.
Try to create it directly in cellForRowAt indexPath: like this. Here no need of tableView.register(UINib(nibName: "TableViewCell", ... line.
//And replace names with your names
var cell = tableView.dequeueReusableCell(withIdentifier:"cell") as? TableViewCell
if cell == nil {
cell = Bundle.main.loadNibNamed("TableViewCell",owner: self, options: nil)?.first as? TableViewCell
}

Failed to Load Custom Cell from dequeue reusable UITableViewCell

I am using xib file to create a custom cell. The reuse identifier is set up in the xib file. Then I have a lazy var that I use to register the nib only once:
private lazy var registerNib: Bool = {
let nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "Custom")
return true
}()
During Cell Creating I just used the lazy var and dequeue the cell from the table view, using the same reuse identifier that I have in the xib file:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let _ = self.registerNib
let cell = tableView.dequeueReusableCell(withIdentifier: "Custom") as! CustomCell
return cell
}
But the unwrapping fails and the app crashes.
tableView.dequeueReusableCell returns nil
for some reason....
There are two methods named dequeueReusableCell.
dequeueReusableCell(withIdentifier:)
dequeueReusableCell(withIdentifier:for:)
But the unwrapping fails and the app crashes. tableView.dequeueReusableCell returns nil for some reason....
You are using the first one and the doc clearly says
Return Value
A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
You may want to use the latter.
Change the line:
let cell = tableView.dequeueReusableCell(withIdentifier: "Custom") as! CustomCell
To:
let cell = tableView.dequeueReusableCell(withIdentifier: "Custom", for: indexPath) as! CustomCell
You need to register your nib object in viewDidLoad(): method like this
let nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "Custom")
Also, did you set the cell reuse identifier in the storyboard?

TableCell into Table View in swift

Basically I need to do what is done here - Not able to add static UITableViewCell into tableview
But I need to do it in swift and I do not know how to convert the objective C solution into swift
Image of the solution I need in swift
First this is not the place to ask for code sample. You should have a look to solutions like Codementor where you can find exactly the kind of help you need ;)
They are different approaches to your problem.
First, you are using a xib, which makes it impossible to add cells in it.
Instead you couldd use a storyboard. In that case you'll be able to do whatever you want and add custom cell.
1 - If you really have to use xib, then you can load custom cells by using alanlo approach. I would suggest to use an extension to register your custom cell like so:
extension UITableViewCell {
class func register(tableView: UITableView) {
let identifier = String(describing: self)
let nib = UINib(nibName: identifier, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: identifier)
}
}
Note that your cell identifier will need to have the same name as your custom tableviewcell class (here it would be YourCustomCellTableViewCell)
2- Then in viewdidload:
YourCustomCellTableViewCell.register(tableView: yourTableView)
3 - Then thanks to the fallowing extension you can easily dequeue your cell:
extension UITableView {
func dequeue<T: UITableViewCell>(indexPath: IndexPath) -> T {
let identifier = String(describing: T.self)
guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
fatalError()
}
return cell
}
}
4 - dequeue it in the cellForRowAtusing:
let cell: YourCustomTableViewCell = yourTableView.dequeue(indexPath: indexPath)
return cell
Try:
let nibName = "nameOfYourCellNib"
let cell = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? {YOUR_CELL_CLASS_HERE}
May I know whether you are trying to create static cells or dynamic cells?
The solution can be simply changing the cell in the table view instead of adding it in codes or separate xib

UITableView and custom UITableViewCell using .xib

In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class
In my ViewController the code I used to populate and show the cell on the table view is as follows:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let transaction = statementArray[indexPath.row]
let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell
cell.transAmount.text = String(transaction.transAmount)
cell.transDesc.text = transaction.transDesc
cell.transFees.text = String(transaction.transFees)
return cell
}
I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?
First you need to register your custom cell with UITableView
yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")
then in UITableView Delegate method cellForRowAt you need to write
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell
now you can access your UITableViewCell properties with cell.propertyName
and you must take care that "cellIdentifier" and "forCellReuseIdentifier" both value must be same.
One more thing is you need to register your class for reuse identifier in viewDidLoad method.
YourTable.registerclass(tablecell, forCellReuseIdentifier: "identifier"
And make sure you have connect all the required outlets.
FIrst Register Custom cell nibCalss in tableview
let str1 : NSString = "StatementCell"
tableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: str1 as String)
Now initialise tableviewcell
let cell1:StatementCell = tableView.dequeueReusableCell(withIdentifier: str1 as String) as! StatementCell!
Now access tableviewcell outlet collection.

iOS Swift 3 tableview custom cell error

I am trying to add a custom cell to tableview in Swift3 but getting a strange error. Here is the screenshot of error.
Write indexPath in place of IndexPath like this:
let cell = tableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
Also, make sure that CustomCell is subclass of UITableViewCell.
Replace the placeholder IndexPath with lowercase indexPath
Placeholders – with a light blue background – are tokens which indicate the expected types of the parameters.
But you got more serious issues than that error.
Your CustomCell class does not inherit from UITableViewCell. Change it to:
class CustomCell:UITableViewCell {
// your custom cell implementation
}

Resources