I have strange behavior with UITableView on Storyboard today. I have created UITableView on Storyboard. After that I drag a PrototyleCell to this table and choose style is Basic. And I implement DataSource and Delegate on my ViewController. It show to simulator normal. But I can't tap to table for select a cell and didSelectCellAtIndexPath don't work too. In Storyboard I have checked selectionStyle. If I change style to another style, It work normally.
So my question is: this is a bug or it is a behavior of UITableView? And anyone can give some explanation for it.
Here is my code: Problem Cell Code. I can't select when use it but when I set another style of cell on storyboard everything will ok.
Thanks in advance
No its neither bug nor normal behavior, you must be doing some basic mistake...
Try following code with tableview and prototype cell in storyboard, Everthing will work.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var dataSource = ["Ajay","Ajay","Ajay","Ajay","Ajay","Ajay"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .Value1, reuseIdentifier: "cell")
}
cell!.textLabel?.text = dataSource[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.row)
} }
Have you added the
tableView: cellForRowAtIndexPath delegate method. This is a required delegate you must implement.
Related
I want to use https://github.com/intuit/AnimatedFormFieldTableViewCell in my project but I can’t get my head around the steps for setting it up. So far, I’ve dragged the files from the folder and followed the steps as:
In order to use AnimatedFormFieldTableViewCell, all you have to do is:
1) Register the AnimatedFormFieldTableViewCell nib on the ViewController on which you are implementing your UITableView for your reuse identifier.
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerCellNib(AnimatedFormFieldTableViewCell)
tableView.reloadData()
}
2) Dequeue your cell on CellForRowAtIndexPath as a AnimatedFormFieldTableViewCell.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! AnimatedFormFieldTableViewCell
return cell
}
3) Change the placeholder's label text by calling setLabelText on the cell itself.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! AnimatedFormFieldTableViewCell
cell.setLabelText("Enter title")
return cell
}
Notes:
1) You can still implement UITextFieldDelegate the same way you would implement on a regular UITextField, you just need to define the AnimatedFormFieldTableViewCell's delegate (there is no need to directly define the delegate for the embedded UITextField).
2) In order to access the embedded UITextField you can simply call the cell's cellTextField property.
I don’t get these last two steps.
If I run my app, I get the unexpectedly found nil on self.cellTextfield.delegate = self in the AnimatedFormFieldTableViewCell class.
What am I missing?
Hi waseefakhtar your code does not miss anything. just the only problem is you registered the nib with the wrong way that's why you got the unexpectedly found nil error on self.cellTextfield.delegate = self.
try this code:
let myNib = UINib.init(nibName: "AnimatedFormFieldTableViewCell", bundle: nil)
self.tableView.registerNib(myNib, forCellReuseIdentifier: "cell")
PS: just be aware that registerNib method syntax can differ depending on the swift version
My code is here, I don't know where you clerical error, but you can check my code to find out:
import UIKit
class ViewController2: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// register a nib like below
let nib:UINib = UINib.init(nibName: "AnimatedFormFieldTableViewCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "AnimatedFormFieldTableViewCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 88.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnimatedFormFieldTableViewCell", for: indexPath as IndexPath) as! AnimatedFormFieldTableViewCell
cell.setLabelText("Enter title")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
The result:
So, just check the steps, where you go wrong.
The documentation notes this:
There is no need to directly define the delegate for the embedded UITextField
The instruction is to do the following:
You just need to define the AnimatedFormFieldTableViewCell's delegate
You'll want to set the AnimatedFormFieldTableViewCell's delegate rather than the cellTextField's delegate, so:
self.delegate = yourUITextViewDelegate
rather than self.cellTextField.delegate = yourUITextViewDelegate (this is wrong)
This is what the documentation describes
Edit: OP clarified that the delegate assignment code is not in their class; it's in the pod's class. I'm considering deleting this answer as I don't think it is solving the problem.
Numerous tutorials I've been through say the only code I need to display the array I want it to is:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var chatListTableView: UITableView!
var friends = ["Anthony", "Antonio", "Andy"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ChatListCell")
cell.textLabel.text = self.friends[indexPath.row]
return cell
}
}
However, when I run the app, the tableView is still blank. What am I doing wrong? I feel that I am missing something.
All I want to do is display the array in the tableView.
Check if the ViewController is the datasource and delegate of the tableview
As Aci says in his answer, you have to set the data source and delegate of the table view to your view controller. The easiest way to do that is in Interface Builder.
New to IOS development and am having trouble with handling cell selection on a table. Whenever I select, the method is not getting called below - any idea why?
My project structure is:
View Controller -> View -> Table View
The below code demonstrates the method calls. The others get called no problem! I know touch is working as pull down successfully refreshes and on clicking a cell it does become highlighted.
import UIKit
class ViewController: UIViewController, UITableViewDelegate
{
let blah = ["blah1"]
//How many sections are in the table?
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//How many rows? (returns and int)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blah.count
}
//table contents for each cell?
//Each time this is called it'll return the next row and thus build a table...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("Populating each cell of table view!\n")
tableView.rowHeight = 80.0
var cell = UITableViewCell()
var(a) = blah[indexPath.row]
var image : UIImage = UIImage(named: a)!
cell.imageView.image = image
return cell
}
//Code Cell Selected
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
println("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableViewDelegate, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("wananananaanan" )
println("You deselected cell #\(indexPath.row)!")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Everybody is mentioning to set dataSource and delegate of the tableView.
But after setting also not working fine then sometimes it may happen because of none or disable selection of table view.
To enable it
Go to storyboard -> Select tableView -> click on the attribute inspector ->go to selector -> Select selection as single selection (or multiple selection according to the requirements.)
Please find attached screenshot for your suitability.
You have to set an #IBOutlet to the tableView in you ViewController and set as it's delegate and dataSource to you can see the data an respond to changes in the tableView.
Something like this :
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
And implements the UITableViewDataSource protocol too.
Or you can too in the Interface Builder set the ViewController as it's delegate and dataSource (more easy to do I think) and avoid to set manually in code like above. Is up to you.
I hope this help you.
SWIFT 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Do here
}
Use the above delegate method in swift 3
Couple of checks that can help you:-
myTableView.allowsSelection = true
myTableView.delegate = self
Make sure you written didSelectRowAt correctly:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
If you are using UIButton on UITableViewCell then it overlaps cell so check Solution here
I faced the same issue when compared two identical code examples where one was working well and the other was not calling didSelectRowAtIndexPath
Take a look at two possible ways to solve the issue:
1) In the code itself:
#IBOutlet weak var table: UITableView!
override func viewDidLoad() {
table.delegate = self
table.dataSource = self
//data source might be already set if you see contents of the cells
//the main trick is to set delegate
}
2) Using Storyboard or Document Outline (which was the problem in my case cause storyboard changes are not visible in .swift controller classes.
Open Document Outline and Control + Press your TableView
you will see two outlets called "delegate" and "dataSource"
drag them 1 by 1 to the containing ViewController (right onto the yellow circle)
That's it!
Another caveat is tap gesture recognizers. It's a common use case to use tap gesture recognizer to handle different logic within your view controllers with table views, whether that's exiting touch control or first responders.
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(tapGesture)
E.G. This line of code handles dismissing a date picker in my application and prevents my tableview from calling didSelectRow delegate method
You have to use this: First take a look what are you extending and then use the tableView method.
class YourViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mUITableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// We need to tell to UITableView that we will add the data by ourselves
self.mUITableView.delegate = self
self.mUITableView.dataSource = self
// Register the UITableViewCell class with the tableView
self.mUITableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
// Setup table data
getEvents()
self.mUITableView.allowsSelection = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// here to create you cell view
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "subtitleCell")
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = "\(tableData[indexPath.row].name) - (\(tableData[indexPath.row].eventStateId))"
cell.detailTextLabel?.text = tableData[indexPath.row].lastUpdate
return cell
}
}
Another reason you may write this function which allowed to click under condition
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
if(indexPath.section == 1){
return true
}
return false
}
Another caveat which took me ages to figure out is to make sure that all three of your Table View, your Cell and your Content View all have User Interaction Enabled. Then in Swift 4, at least, you can use:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
if you are editing your tableView:
tableView.allowsSelectionDuringEditing = true
Another thing to check is the access level for your class & method:
I had a Swift UIViewController class marked #objc public, to make it visible to my objective-c code.
In this context you must add public access to this function, or it will not be called.
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Nothing happened till I've cleaned and built again. :)
I'm a new programmer and I'd like to start with a app where to show a table with an image and a label (dynamic). I can do it wist static table but now I'd like to know how to make it with swift. I'm following various tutorial but all say a easy table only array with text...
I'm sure your help will be useful many new as me...
Tutorial, code, are good accept...
import UIKit
class FirstViewController: UIViewController,UITableViewDelegate {
#IBOutlet weak var smilefoto: UIImageView!
var cellContent = ["Rob", "Kirsten", "Tommy", "Ralphie"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellContent.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "tabella")
cell.textLabel?.text = cellContent[indexPath.row]
return cell
}
}
What you'll have to do is create a custom UITableViewCell class, where you can create an imageview and label and anything else.
You should check this tutorial out:
https://www.youtube.com/watch?v=JG_AMY_gSDQ
And when you've done this, you'll have access of every object in that cell through that class:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProgramCell", forIndexPath: indexPath) as YourCustomTableViewCell
cell.yourCellImage = cellContent[indexPath.row].yourImage
return cell
}
Also dont forget to link the tableView outlet from the storyboard to this viewController and set the DataSource to self (inherits from UITableViewDataSource)
i have been busting my brain trying to figure out how this works, but i can't seem to get it. i have tried using other tutorials, but with the many beta releases, everything keeps changing. i am fairly new to IOS development, so i'm kind of struggling.
in storyboard i have UITableView, which contains a cell with the identifier "myCell".
here's what i have so far. when i run the IOS simulator, nothing is presented on the table view.
any suggestions on how to fix this?
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "Cell #: \(indexPath.row)" // display the row number
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10; // testing out with 10 cells
}
}
Add the function
optional func numberOfSectionsInTableView(tableView: UITableView) -> Int
and return the number of sections you want.
You should make sure in the storyboard your UITableViewController has the class ViewController like so:
and that ViewController is both the delegate and datasource of the UITableViewController like so (Referencing Outlets):
You should also check that your UITableViewController is set to initialViewController if you don't see any lines at all (check the one at the bottom).