UITableView Prototype cell not found - swift

every one.
After lots of search and different test my code doesn't work yet...
I try to do a simple UITableView with a simple Prototype cell whit using "dequeueReusableCellWithIdentifier" but this function doesn't found my Prototype Cell.
My code :
import Foundation
import UIKit
class DanceClubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableViewSound: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.tableViewSound.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellVote")
self.tableViewSound.dataSource = self
self.tableViewSound.delegate = self
self.tableViewSound.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
#IBAction func backToViewPlay(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int)->Int
{
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : UITableViewCell = self.tableViewSound.dequeueReusableCellWithIdentifier("cellVote") as UITableViewCell
return cell
}
If anyone had already had this problem?
The identifier for my Prototype Cell is : cellVote

The key to address your label is to create a custom TableViewCell class in another file:
import UIKit
class DanceCell: UITableViewCell {
#IBOutlet weak var num: UILabel! //connect the label
}
Then for your ViewController:
import Foundation
import UIKit
class DanceClubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableViewSound: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.tableViewSound.dataSource = self
self.tableViewSound.delegate = self
self.tableViewSound.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
#IBAction func backToViewPlay(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func tableView(tableViewSound:UITableView, numberOfRowsInSection section:Int)->Int
{
return 10
}
func tableView(tableViewSound: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableViewSound.dequeueReusableCellWithIdentifier("cellVote", forIndexPath: indexPath) as DanceCell
cell.num.text = "Hello"
return cell
}
}
I removed some stuff, and added he key line in the 'cellForRowAtIndexPath' function to register the cell. I then was able to communicate with the label. Make sure the prototype cell has set 'cellVote' as the identifier in at attributes inspector.

Related

How to UITableView Click image and title

I've created a tableView, but when I click it, I don't get any results. I wanted to add a new feature to improve my project, but I couldn't add the videos I watched and the things I researched.
Table View
import UIKit
class ViewController1: UIViewController {
#IBOutlet weak var FoodView: UITableView!
let dogfoods = ["pork", "banana", "chicken-leg"]
override func viewDidLoad() {
super.viewDidLoad()
FoodView.delegate = self
FoodView.dataSource = self
// not tapped no see
FoodView.allowsSelection = false
}
}
extension ViewController1: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dogfoods.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FoodView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
let dogfood = dogfoods[indexPath.row]
cell.foodImageView.image = UIImage(named: dogfood)
cell.nameLabel.text = dogfood
return cell
}
}
CustomCell
class CustomCell: UITableViewCell {
#IBOutlet weak var dogView: UIView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var foodImageView: 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
}
}
When I click on one of the cells in the picture, I want to write a larger version of the picture and a description, how can I do this? When I searched on the internet, I applied similar ones, but I couldn't get any results.
You have a few choices. You can add one or more buttons to your custom cell. You can attach a tap gesture recognizer to your cell's content view.
Probably the easiest way to respond to a tap on the whole cell is to have view controller conform to the UITableViewDelegate protocol and implement the tableView(_:didSelectRowAt:) method.
That method will be called when the user selects a cell, and you would use the indexPath of the tapped cell to figure out which one was tapped and do whatever is appropriate.
You can do that with easy and efficient way using Delegate in Swift
//create protocol as we used interface in Java
#objc protocol TableViewCellDelegate {
#objc func click(indexPath: IndexPath?)
}
// Modify your class CustomCell as:
#IBOutlet weak var dogView: UIView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var foodImageView: UIImageView!
var delegate: TableViewCellDelegate?
var indexPath: IndexPath?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
foodImageView.isUserInteractionEnabled = true
foodImageView.addGestureRecognizer(tapGestureRecognizer)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
let tappedImage = tapGestureRecognizer.view as! UIImageView
self.delegate.click?(indexPath: self.indexPath)
}
// Modify your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) in ViewController1 as
let cell = FoodView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
cell.delegate = self
cell.indexPath = indexPath
let dogfood = dogfoods[indexPath.row]
cell.foodImageView.image = UIImage(named: dogfood)
cell.nameLabel.text = dogfood
return cell
// And now add extension add the end of ViewController1
extension ViewController1: TableViewCellDelegate {
func click(indexPath: IndexPath?) {
// open image for preview here
}
}
You can do it in many ways
use a add a UITableViewDelegate method which is
override func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath){
//your code...
}
it will called every time when cell clicked.
if you prefer to trigger any button click rather then cell click then go for delegate (Izaan Saleem already explained), or you can use NotificationCenter, but for this task I prefer didSelect or delegate solution.

'UITableView' does not have a member in dequeneResusableCell

I can't figure out how to solve this. It keeps throwing an error with the dequeneResuableCell. I've tried every variable available. I have xcode 6. I removed the outlets, because they are not the problem and I have not included the constructor/iniitalization for the HospitalList class.
This is the code
import UIKit
class HospitalList: UIViewController {
#IBOutlet weak var hospitals: UITableView!
var Hos: [Hospital] = []
override func viewDidLoad() {
super.viewDidLoad()
Hos = createArray()
hospitals.delegate = self
hospitals.dataSource = self
}
func createArray() -> [Hospital] {
\\more code to create an array of Information
return tempHospitals
}
}
extension HospitalList: UITableViewDelegate, UITableViewDataSource {
//counts number of elements in Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return Hos.count
}
//sets up whats in the table view
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let Hop = Hos[indexPath.row]
// this line is the problem right here
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoHospitals")
cell.HName.text = Hop.name \\and more, but not including
return cell
}
return UITableViewCell
}

How do I call a different function for each TextField in a UITableView (Swift)?

I have a UITableView and my prototype cell consists of a label and a TextField. I also have a class MyClass that contains functions func1, func2, fun3, ... I have several ViewControllers that use the same tableViewCell prototype. Each viewController will have an instance of MyClass, called inst1, inst2, and inst3. When I enter text into FirstViewController's TableView I want each row to call a function from the instance of MyClass that corresponds to the row.
So when I enter text into row 1 on the FirstViewController I want to pass the data entered into the textField into func1 of inst1. When data is entered into row 2 of FirstViewController I want the data in the textfield to be passed into func2 of inst1. And so on and so forth down the rows.
I am very new to this and would really appreciate some help figuring out how to do this. Let me know if that doesn't make sense and I can try to rephrase it. I really need help with this. Thanks in advance!
*Updated question to show my code
Below is my Code:
FirstViewController.swift
extension FirstViewController: MyCellDelegate {
func MyCell(_ cell: UITableViewCell, didEnterText text: String) {
if let indexPath = tableView.indexPath(for: cell) {
if (indexPath.hashValue == 0) {
inst1.func1(one: text)
}
if (indexPath.hashValue == 1) {
inst1.func2(two: text)
}
}
totalText.text = inst1.getMyTotal()
}
}
import UIKit
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let inst1 = MyClass()
#IBOutlet weak var totalText: UILabel!
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 11
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell") as! TableViewCell
let text = cell.cellData[indexPath.row]
cell.myTextField.tag = indexPath.row
cell.delegate = self
cell.myLabel.text = text
cell.myTextField.placeholder = text
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
TableViewCell.swift
import UIKit
protocol MyCellDelegate: class {
func MyCell(_ cell: UITableViewCell, didEnterText text: String)
}
class TableViewCell: UITableViewCell {
weak var delegate: MyCellDelegate?
public var cellData: [String] = ["1","2","3","4","5","6","7","8","9","10","11"]
#IBOutlet weak var myLabel: UILabel!
#IBOutlet weak var myTextField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
}
When I set a breakpoint in the FirstViewController extension it never runs that code.
In WillDisplayCell add the tag to the UITextField. Also create a protocol to notify the Corrosponding viewController and set itself as the delegate here.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
cell.textField.tag = indexPath.row
cell.delegate = self
}
The protocol in your cell class will look something like this
protocol MyCellDelegate: class {
func MyCell(_ cell: UITableViewCell, didEnterText text: String)
}
class MyCell: UITableViewCell, UITextFieldDelegate {
weak var delegate: MyCellDelegate?
override fun awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
//All the remaining code goes here
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
delegate?.MyCell(self, didEnterText: textField.text! )
return true
}
}
Now again in your FirstViewController which has conformed to be its delegate do this
extension FirstViewController: MyCellDelegate {
func MyCell(_ cell: UITableViewCell, didEnterText text: String) {
if let indexPath = tableView.indexPathForCell(cell) {
// call whichever method you want to call based on index path
}
}

Not able to display anything on table view Swift

This is my history view, I have a tableview inside view controller. But for some reason i can't output anything, I am trying to hardcode it and its not displaying anything at all. One thing i know is i need to make tableView functions override and if i do that i get error.
import UIKit
class History: UIViewController, UITableViewDataSource, UITableViewDelegate
{
#IBOutlet var tableView: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "newBackground.jpg")!)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath) as! historyCell
cell.durationLabel.text = "98"
return cell
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
}
}
heres my class for the cell prototype, and i made sure that the identifier is also "historyCell"
public class historyCell: UITableViewCell{
#IBOutlet var durationLabel: UILabel!
#IBOutlet var kicksLabel: UILabel!
}
How did you connect your prototype cell's controls to the IBOutlets in you historyCell class ? I didn't know that was possible when you're not using a UITableviewController. I've been using tags all this time.
Unless there's something new that I wasn't aware of, your assignment to cell.durationLabel.text should cause unwrapping of a nil (is that the error you're getting ?)

Passing data from tableView to ViewController in Swift

I have an App that i'm trying to adapt exactly how i want
I have been following a Youtube tutorial of Seemu Apps to make it but I need to finish it adding an optional ViewController
This app has 2 tableViews showing vehicles and if we click in one row of the first tableView then second tableView will show us a list of selected vehicles.
Here is what we have until now: (image link , because i haven't got ten points reputation on stackOverFlow)
http://subefotos.com/ver/?65ba467040cb9280e8ec49644fd156afo.jpg
All is running perfect, but i want to be able to display information in an optional detailViewController (label with a detailed description of each vehicle and a bigger image of this ) depending of which vehicle we click in the secondTableViewControlle (or modelViewController in the App) exactly how i was following in the tutorial between tableViews
i know that we need to passing data through prepareForSegue method , i have understood this making the steps in the tutorial but when we have 2 tableviewControllers
For example : if we want to display a last viewController with information of Ferrari 458 and a great picture of this car
What do we need to do exactly to show information of each vehicle?
PD : I'm beginner in the programming world, maybe i would need to see it in a very simple way
The whole code:
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var selMake = String()
#IBOutlet var tableView : UITableView!
var transportData : [String] = ["Car", "Plane", "Motorcycle", "Truck" , "Train", "Bicycle" , "Helicopter"]
//////////////////////////////////////////
//viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//Register custom cell
var nib = UINib(nibName: "customCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
//Numbers of rows in Section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.transportData.count
}
//cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
///// Static Cell (no valid for custom cells)
/*
var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.transportData[indexPath.row]
return cell
*/
var cell:customCellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCellTableViewCell
cell.lblTrans.text = transportData[indexPath.row]
cell.imgTrans.image = UIImage (named: transportData[indexPath.row])
return cell
}
//height
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 90
}
//didSelectRowAtIndexPath
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Fila \(transportData[indexPath.row]) seleccionada")
selMake = transportData[indexPath.row]
performSegueWithIdentifier("modelView", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "modelView") {
var vc = segue.destinationViewController as modelViewViewController
vc.selMake = selMake
}
}
import UIKit
class customCellTableViewCell: UITableViewCell {
#IBOutlet weak var imgTrans: UIImageView!
#IBOutlet weak var lblTrans: 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
}
}
import UIKit
class modelViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//////////////////////////////////
var selMake = String()
var tableData : [String] = []
#IBOutlet var tableView: UITableView!
//////////////////////////////////
override func viewDidLoad() {
super.viewDidLoad()
//Register custom cell
var nib = UINib(nibName: "customCell2", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
switch selMake {
case "Car" :
tableData = ["Ferrari 458", "La Ferrari"]
case "Plane" :
tableData = ["Iberia"]
case "Motorcycle" :
tableData = ["Kawasaki Ninja", "Yamaha Aerox"]
case "Truck" :
tableData = [ "Camion transporte"]
case "Train" :
tableData = [ "Ave" ]
case "Bicycle" :
tableData = ["BMX"]
case "Helicopter" :
tableData = ["HelicopteroCombate"]
default:
println("Sel Make \(selMake)")
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/* var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.tableData[indexPath.row]
return cell*/
var cell:customCell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCell2TableViewCell
cell.lbl2text.text = self.tableData[indexPath.row]
cell.img2image.image = UIImage (named: tableData[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Row \(indexPath.row)selected")
performSegueWithIdentifier("detailView", sender: self)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 90
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
var vc = segue.destinationViewController as DetailViewController
}
}
import UIKit
class customCell2TableViewCell: UITableViewCell {
#IBOutlet var lbl2text: UILabel!
#IBOutlet var img2image: 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
}
}
import UIKit
class DetailViewController: UIViewController {
#IBOutlet var imgDetail: UIImageView!
#IBOutlet var lblDetail: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
Try this.
ModelViewViewController
var selectedImage:String?
var selectedLabel:String?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Row \(indexPath.row)selected")
selectedImage = self.tableData[indexPath.row]
selectedLabel = self.tableData[indexPath.row]
performSegueWithIdentifier("detailView", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
var vc = segue.destinationViewController as DetailViewController
vc.img = selectedImage
vc.lblDetail = selectedLabel
}
}
class DetailViewController: UIViewController {
#IBOutlet var imgDetail: UIImage!
#IBOutlet var lblDetail: UILabel!
var img:String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imgDetail = UIImage(named: img)
}
This should work.