I have a bunch of UITableViews in my app that essentially do the same thing, so I created a protocol called Presenter and made them all conform to it. For simplicity I decided to implement UITableViewDelegate and UITableViewDataSource methods within extensions of said protocol. However, I stumbled upon multiple errors and warnings as shown below:
Adding #objc to the protocol did not help.
Now I know that making a subclass of UITableView may be easier, but I was wondering if there is a painless solution to this problem. As someone just getting acquainted with Swift, I'm trying to implement protocols as much as I can.
Here's the code:
protocol Presenter {
var viewer: Viewer { get }
}
extension Presenter where Self: UITableViewDelegate {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewer.header
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return viewer.height
}
}
extension Presenter where Self: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewer.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: GenericCell.identifier, for: indexPath) as! GenericCell
cell.content = viewer.viewable(at: indexPath.row)
return cell
}
}
I want to execute a single line of code when the user selects a cell in my TableView. At runtime, my TableView populates with data okay, and the cells are indeed clickable/selectable. But, when a cell is selected, the 'didSelectRowAtIndexPath method is skipped/not called. I'm new to Swift, so maybe I'm overlooking something very simple. The structure of my code is as follows:
import UIKit
class TopicsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Number of Sections:
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 }
//Number of Rows in Each Section:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->Int { return 3 }
//Contents of Each Cell:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel?.text = "Data"
}
//Code below is skipped/ignored at runtime, no matter what I try:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Hello!")
}
Note: I am not using a gesture recognizer (other threads on this subject suggest a gesture controller could be the culprit)
Did you assign the "delegate" of the tableview?
I'm trying to add in-app purchase to my app. But I've no knowledge about how to add in app purchase. That's why I'm following this guide. According to guide I added UITableViewDelegate, UITableViewDataSource, SKProductsRequestDelegate protocols. Unfortunately I got an error shown below. What is the problem and how can I solve it?
import UIKit
import StoreKit
class IAPurchaceViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SKProductsRequestDelegate {
You must implement the required delegate methods of the delegate's REQUIRED protocols
I'll show you, I just tried this and it works: here's the methods you need to add, at minnimum in fact, here's an example, this is all you need:
import Foundation
import UIKit
import StoreKit
class ANExample: UIViewController, UITableViewDataSource, UITableViewDelegate, SKProductsRequestDelegate {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return A_CEll //you must code this
}
func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return A_NUMBER // you must code this!
}
}
the protocol for the StoreKit stuff is this:
protocol SKProductsRequestDelegate : SKRequestDelegate, NSObjectProtocol {
// Sent immediately before -requestDidFinish:
#availability(iOS, introduced=3.0)
func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!)
}
the protocol for table datasource is this:
protocol UITableViewDataSource : NSObjectProtocol {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
optional func numberOfSectionsInTableView(tableView: UITableView) -> Int // Default is 1 if not implemented
optional func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different
optional func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String?
// Editing
// Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
optional func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
// Moving/reordering
// Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
optional func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool
// Index
optional func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! // return list of section titles to display in section index view (e.g. "ABCD...Z#")
optional func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int // tell table which section corresponds to section title/index (e.g. "B",1))
// Data manipulation - insert and delete support
// After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change
// Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead
optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
// Data manipulation - reorder / moving support
optional func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
}
the protocol for tableview is this:
protocol UITableViewDelegate : NSObjectProtocol, UIScrollViewDelegate {
// Display customization
optional func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int)
// Variable height support
optional func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
optional func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
optional func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat
// Use the estimatedHeight methods to quickly calcuate guessed values which will allow for fast load times of the table.
// If these methods are implemented, the above -tableView:heightForXXX calls will be deferred until views are ready to be displayed, so more expensive logic can be placed there.
#availability(iOS, introduced=7.0)
optional func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
#availability(iOS, introduced=7.0)
optional func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat
#availability(iOS, introduced=7.0)
optional func tableView(tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat
// Section header & footer information. Views are preferred over title should you decide to provide both
optional func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? // custom view for header. will be adjusted to default or specified header height
optional func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? // custom view for footer. will be adjusted to default or specified footer height
// Accessories (disclosures).
optional func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath)
// Selection
// -tableView:shouldHighlightRowAtIndexPath: is called when a touch comes down on a row.
// Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath)
#availability(iOS, introduced=6.0)
optional func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath)
// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
optional func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
#availability(iOS, introduced=3.0)
optional func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
// Called after the user changes the selection.
optional func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
#availability(iOS, introduced=3.0)
optional func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
// Editing
// Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.
optional func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle
#availability(iOS, introduced=3.0)
optional func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String!
#availability(iOS, introduced=8.0)
optional func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? // supercedes -tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: if return value is non-nil
// Controls whether the background is indented while editing. If not implemented, the default is YES. This is unrelated to the indentation level below. This method only applies to grouped style table views.
optional func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool
// The willBegin/didEnd methods are called whenever the 'editing' property is automatically changed by the table (allowing insert/delete/move). This is done by a swipe activating a single row
optional func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath)
optional func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath)
// Moving/reordering
// Allows customization of the target row for a particular row as it is being moved/reordered
optional func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath
// Indentation
optional func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int // return 'depth' of row for hierarchies
// Copy/Paste. All three methods must be implemented by the delegate.
#availability(iOS, introduced=5.0)
optional func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool
#availability(iOS, introduced=5.0)
optional func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject) -> Bool
#availability(iOS, introduced=5.0)
optional func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!)
}
You'll notice that in the protocols above, you have methods tagged as OPTIONAL, you don't need to provide these methods if you don't want to ... HOWEVER, you must provide the OTHER methods at the top of each protocol list that ARE NOT optional. You must use the functions that are REQUIRED in order for your UIViewController to conform to these delegates. IN the above example, the methods I've given you are the only 3 that are required, but you can use all of the methods below if you want to, its your choice, but 3 are required.
Here's more information so that you can learn about this stuff, it's only a little complicated the first time, but once you catch on, it's all pretty simple moving forward. Should you have additional questions, feel free to ask.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html
I want a table view in my view to always be re-orderable. I cannot figure this out. I have rows in my table view but can't get the re-ordering handles to show up.
For the table view prototype cell, I made sure there was a check in Indentation > "Shows Re-order Controls", but this didn't do anything.
This is how my whole class looks like:
class ViewController: UIViewController {
...
#IBOutlet var currentTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
currentTable.editing = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return unitCategories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = "\(unitCategories[indexPath.row])"
return cell
}
/*func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}*/
}
Can someone help point me in the right direction?
You need to implement these two methods in order to be able to show the reordering control,
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
As stated in the header file,
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool
Allows the reorder accessory view to optionally be shown for a
particular row. By default, the reorder control will be shown only if
the datasource implements:
-tableView:moveRowAtIndexPath:toIndexPath:
I am really new to the whole Swift thing and also programming in general. I have researched everywhere but couldn't find an answer for the error that I got. Please help me :)
import Foundation
import UIKit
class TümÜrünlerViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tümÜrünlerTableView: UITableView!
#IBAction func cancelTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
var ürünler = ["Havalı", "Daha Havalı", "Eheheh"]
var ürün = "Balık"
func TableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = UITableViewCell()
cell.textLabel!.text = self.ürünler[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.ürün = self.ürünler[indexPath.row]
self.performSegueWithIdentifier("başlıklardanÖzeleSegue", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tümÜrünlerTableView.dataSource = self
self.tümÜrünlerTableView.delegate = self
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var detailViewController = segue.destinationViewController as BaşlıklarViewController
detailViewController.ürün = self.ürün
if self.ürün == "Havalı" {
detailViewController.label = "anan"
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->Int {
return self.ürünler.count
}
}
Here is my code but I am getting the error when I try to insert UITableViewDataSource. I tried everything that the forums said but it docent seem to work for me :(
My guess:
Let us look at this method. T needs to be decapitalized. tableView not TableView
func TableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = UITableViewCell()
cell.textLabel!.text = self.ürünler[indexPath.row]
return cell
}
It's a very simple mistake - the UITableViewDataSource requires that 2 methods are implemented:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
but you've just made a typo in the 2nd one:
func TableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
^
the method name should start in lowercase: tableView(...)
You have a capital T on your cellForRowAtIndexPath function. It should read:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = UITableViewCell()
cell.textLabel!.text = self.ürünler[indexPath.row]
return cell
}
Reason behind error is that, you are not calling datasource required method in correct order. Correct order of calling is :
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
Always, make sure you call numberOfRowsInSection before cellForRowAtIndexPath.