Custom TableViewCell Swift - ios

Here is the code from my custom cell class:
import UIKit
class CustomOrderTableViewCell: UITableViewCell {
#IBOutlet var MealName: UILabel!
#IBOutlet var MealPrice: UILabel!
#IBOutlet var MealDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func deleteMeal(sender: AnyObject) {
}
}
Here are the table view related functions:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealArray.orderedMeals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("in")
var cell = tableView.dequeueReusableCellWithIdentifier("orderCell", forIndexPath: indexPath) as! CustomOrderTableViewCell
cell.MealName.text = mealArray.orderedMeals[indexPath.row].mealName
cell.MealDescription.text = mealArray.orderedMeals[indexPath.row].mealDescription
let price = NSString(format: "%.2f", mealArray.orderedMeals[indexPath.row].mealPrice) as String
cell.MealPrice.text = "R" + price
return cell
}
The problem is that nothing gets displayed in the table view and func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is never called.
Any solutions? Thanks

If func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is never called that means you have not connected your UITableViewDataSource in IB correctly. Make sure that you connect the dataSource property with your ViewController. Also check that all classes are set for your ViewController, TableView and the Cell itself as this another common mistake.

Related

How to add a delete button to Cells on Swift

I'm trying to create an App but I'm struggling with a simple problem: How can I add a delete button to my custom cells?
I've created a NewCocoaTouchClass
I've created my custom design (added also a button for every cell) and provided the Outlets in the TableViewCellController
I managed to implement my custom cell to another viewController
I created a button on my viewController
I'd like that when the user taps on my new button, cell buttons will appear, and then I can delete cells singularly. When I create the IbAction I can't retrieve the cell code because the cell is defined only in my tableViewCode.
Thank in advance
Ps: I also implemented deleting cells by swipe but my custom cell design is incompatible with the standard rectangular delete option (this is awful).
TableViewCellController
import UIKit
class CustomTableTableViewCell: UITableViewCell {
static let identificatore = "CustomTableTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "CustomTableTableViewCell", bundle: nil)
}
#IBOutlet weak var ImmagineCella: UIImageView!
#IBOutlet weak var TestoCella: UILabel!
#IBOutlet weak var Button: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ViewController
import UIKit
class MaterieViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var materie : [String] = ["zoifvdhfdv", "szvzv", "zdvzfv", "zfdvbfdb", "bfzdfb"]
#IBOutlet weak var TableViewMaterie: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
TableViewMaterie.register(CustomTableTableViewCell.nib(), forCellReuseIdentifier: CustomTableTableViewCell.identificatore)
TableViewMaterie.delegate = self
TableViewMaterie.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return materie.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomTableTableViewCell.identificatore, for: indexPath) as! CustomTableTableViewCell
cell.TestoCella.text = materie[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 67.83
}
#IBAction func EditButton(_ sender: UIButton) {
}
}
This is the code I use in my project
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String?
{
return "Delete"
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
//Add your code
}
}
You can write with add target
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomTableTableViewCell.identificatore, for: indexPath) as! CustomTableTableViewCell
cell.TestoCella.text = materie[indexPath.row]
cell. Button.tag = indexPath.row
cell. Button.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
return cell
}
func buttonClicked(sender: UIButton) {
let buttonRow = sender.tag
print(buttonRow)
}

Edit cell outlets when editing tableview

This is my app:
When i press the Edit button (''Rediger''), i get the following:
So my question is: How do i make the round red circle and the disclosure indicator hidden while the tableview is being edited? Both the circle and the disclosure indicator are imageViews.
Here is the code for the custom cell (i edited out the unnecessary parts):
class KundeavisCell: UITableViewCell {
#IBOutlet weak var unreadImage: UIImageView!
#IBOutlet weak var disclosureIndicatorImage: UIImageView!
}
And the view controller with the table:
class KundeaviserVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var redigerOutlet: UIBarButtonItem!
var stores = ["Rema 1000", "Coop Obs", "Coop Extra"]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "KundeavisCell", for: indexPath) as! KundeavisCell
// Here i edit the cell
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stores.count
}
#IBAction func tableViewEditingPressed(_ sender: Any) {
if tableView.isEditing {
tableView.setEditing(false, animated: true);
redigerOutlet.style = UIBarButtonItemStyle.plain;
redigerOutlet.title = "Rediger";
} else {
tableView.setEditing(true, animated: true);
redigerOutlet.title = "Ferdig";
redigerOutlet.style = UIBarButtonItemStyle.done;
}
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let itemToMove = stores[sourceIndexPath.row]
stores.remove(at: sourceIndexPath.row)
stores.insert(itemToMove, at: destinationIndexPath.row)
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
}
I know i can indent the images to the left by setting constraints on them, but i want to hide them completely. I found a question about it: Link but unfortunately it was written 5 years ago and in Objective-C.
Any help will be highly appreciated, thanks!
That code you reference is still valid to now. You already have the Custom implementation of the UITableViewCell so now implement the SetEditing function and in the implementation hide/shows your images.
override func setEditing(_ editing: Bool, animated: Bool) {
unreadImage.isHidden = editing
disclosureIndicatorImage.isHidden = editing
}
That should work.

Tableview's delegate methods are not calling

I am trying to use tableview with delegate methods.
But it is not working.
My class:
class IsteklerTVVC: UITableViewController {
#IBOutlet var mainTable: UITableView!
let missionControl = MissionControl.sharedInstance
var yardimList:[YardimIstek] = [YardimIstek]()
override func viewDidLoad() {
super.viewDidLoad()
mainTable.delegate=self
mainTable.dataSource=self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
veriGetir()
}
func veriGetir() {
let parameters: Parameters = [
"uid": missionControl.id
]
Alamofire.request("domain.com", method: .post, parameters: parameters).responseJSON { response in
print("istek eklendi \(parameters)")
let json = JSON(response.result.value)
for (key,subJson):(String, JSON) in json {
print(subJson[0]["tarih"].string)
let blok=YardimIstek()
blok.id=0
blok.isim="Name"
blok.tarih=subJson[0]["tarih"].string!
blok.lat=subJson[0]["lat"].string!
blok.long=subJson[0]["long"].string!
self.yardimList.append(blok)
}
DispatchQueue.main.async {
self.mainTable.reloadData()
print("ok \(self.yardimList.count)")
}
}
}
let textCellIdentifier = "mainCell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yardimList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: isteklerCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier) as! isteklerCell
let row = indexPath.row
let blok=yardimList[row]
cell.setCell(blok: blok)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
}
class isteklerCell: UITableViewCell {
#IBOutlet weak var isimSoyisim: UILabel!
#IBOutlet weak var zaman: UILabel!
func setCell(blok: YardimIstek) {
isimSoyisim.text=blok.isim
zaman.text=blok.tarih
}
}
The problem is, no delegate methods are getting called. I think there is a problem with names. Because when I was using Swift 2, I used the tableview's outlet name as "tableView" and it was working well. Now Swift 3 is not allowing that naming.
So my tableview is looking empty even there is data in yardimList dictionary.
How can I resolve this?
Your delegate function signatures are wrong. They were updated with swift 3:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Two things to check:
First one is do you need the mainTable property? UITableViewControllers comes with a UITableView property called tableView. If you don't need 'mainTable', you can just replace it with tableView.
Second, if you do need mainTable, then you need to make sure you connected the #IBOutlet to the UITableView you want to use.

TableView cellForRowAtIndexPath is never called (iOS, Swift)

I have a problem with creating a table view in UITableViewController. I have tried everything I have found, reuseIdentifier is set correctly, number of rows returns non-zero number and height is set in storyboard. Only the cellForRowAtIndexPath is not called, other table functions runs correctly.
Here is the code:
TableViewController:
import UIKit
import Photos
class CropTableViewController: UITableViewController {
var photos = [Photo]()
var photoAssets = [PHAsset]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CropTableViewCell
let photo = photos[indexPath.row]
cell.photoImageView.image = photo.photo
return cell
}
}
TableViewCell:
import UIKit
class CropTableViewCell: UITableViewCell {
#IBOutlet weak var photoImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The photos array is empty, so photos.count is zero, so numberOfRowsInSection returns 0, so the runtime knows that there are no cells and that there is no need to call cellForRowAtIndexPath.

UITableView is not displaying content in cell

For a project, I've three UITableViews in an UITabbarController. The initial view loads the tableview correctly, but when I tap on the second tab, the table loads the right amount of cells and the right cell class, but don't show the content on it.
I logged the method tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) and every cell gets the right string values.
This is the code I use:
import UIKit
import RealmSwift
class Hapjes: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tabel: UITableView!
let realm = try! Realm()
let productArray = try! Realm().objects(Product).filter("categorie = 1")
override func viewDidLoad() {
super.viewDidLoad()
tabel.dataSource = self
tabel.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Hapjes"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProductenCellHapjes", forIndexPath: indexPath) as! ProductenCell
var object = productArray[indexPath.row]
cell.label.text = object.valueForKey("productNaam") as! String
cell.plaatje.image = UIImage(named: "1449032338_news.png")
let tmp = object.valueForKey("productNaam") as! String
print("Hapje: \(tmp)")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
ProductenCell.swift:
import UIKit
class ProductenCell: UITableViewCell {
#IBOutlet weak var plaatje: UIImageView!
#IBOutlet weak var label: UILabel!
}
This is the screenshot of the UI how it goes now:
http://i.stack.imgur.com/Gx0Jw.png
Thanks for your help.

Resources