In the application, I have custom protocols that my UIViewController conforms to. I have a custom tableViewCell class and have UIImageView and UITextView in there. I set the cell's delegate to the UIViewController after dequeuing. However only one of the custom protocols makes the callback (imagepicker protocol).
protocol customProtocol1{
func pickImage(myInt: Int)
}
protocol customProtocol2{
func protocol2 (myInt: Int)
}
class controller1: UIViewController, UITableViewDelegate, customProtocol1, customProtocol2 {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomTableCellClass
cell.delegate = self
return cell
}
func pickImage ( myInt: Int){
print("This line prints")
}
func protocol2 (myInt: Int){
print ("This line doesn't print")
}
}
And here's the customTableCellClass code:
class CustomTableCellClass: UITableViewCell, UITextFieldDelegate, UITextViewDelegate {
var imageDelegate: customProtocol1?
#IBAction func pickImage( sender: AnyObject) {
imageDelagate?.pickImage(205)
}
var somethingElseDelegate: customProcotol2?
#IBActon func clickOnButton( sender: AnyObject) {
print("this line prints")
somethingElseDelegate?.protocol2(2)
}
override func awakeFromNib(){
super.awakeFromNib()
}
}
My question is, why does the first protocol get callbacks but second does not?
From what I see in your code, you only set one delegate, change your code in cellForRowAtIndexPath to
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomTableCellClass
cell.imageDelegate = self
cell.somethingElseDelegate = self
return cell
}
Your custom cell has two delegate properties, imageDelegate and somethingElseDelegate, but in your implementation of tableView(tableView:cellForRowAtIndexPath:) you only assign one property.
If you set both properties your implementation should work.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomTableCellClass
cell.imageDelegate = self
cell.somethingElseDelegate = self
return cell
}
Related
I am trying to display a textfield on a tableview using a custom cell. I think I have set up the delegation protocol properly, but when loaded, the tableview doesn't show the textfield. I have added a textfield into the customcell, set the class to CustomCell, and changed the identifier to "Cell", but I am not sure what else I am missing.
view controller with tableview:
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Hello")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.cellDelegate = self
cell.contentView.bringSubview(toFront: cell.textField)
cell.textField.delegate = self as? UITextFieldDelegate
cell.textField.text = "Test"
return cell
}
func didPressTextField(indexPath: IndexPath) {
print("textfield was tapped")
}
custom cell VC:
protocol CustomCellDelegate : class {
func didPressTextField(indexPath: IndexPath)
}
class CustomCell: UITableViewCell {
weak var cellDelegate: CustomCellDelegate?
var indexPath: IndexPath!
override func awakeFromNib() {
super.awakeFromNib()
self.cellDelegate = nil
// Initialization code
}
#IBOutlet weak var textField: UITextField!
#IBAction func textFieldWasTapped(_ sender: UITextField) {
self.cellDelegate?.didPressTextField(indexPath: indexPath)
}
Your data source is empty.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// data is not containing any value
return data.count
}
Check data.count it should have some data and also if that is custom cell with XIB then you need to register cell in view didload
self.tableView.register(UINib(nibName: "Your Cell XIB name", bundle: nil),
forCellWithReuseIdentifier: "Cell")
Check your data.count. it must return value greater than 0 otherwise your tableView is showing with 0 rows and nothing is display in tableView.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// debug at this point check what is value of data.count its must be greater than 0
return data.count
}
I have a tableview that is added programatically below that I want to hook up the delegate and dataSource to an external class. The code looks right however the tableview gets added to the view without getting the cell layout from the external class.
let tableView: UITableView = {
let dataService = ActivityDataService()
let tb = UITableView()
tb.tableHeaderView = nil
tb.tableFooterView = nil
tb.rowHeight = 50
tb.estimatedRowHeight = 50
tb.dataSource = dataService
tb.delegate = dataService
tb.register(ProfileActivitySubCell.self, forCellReuseIdentifier: "tableCell")
return tb
}()
Here is the activity service class:
class ActivityDataService: NSObject, UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! ProfileActivitySubCell
return cell
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 0
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
Thanks
When using a UITableView thats not in a storyboard or similar you need to register the cell with an identifier.
Depending on your UITableViewCell (if its a subclass and/or if you are using nibs or not)
You could use one of these methods:
open func register(_ nib: UINib?, forCellReuseIdentifier identifier: String)
open func register(_ cellClass: Swift.AnyClass?, forCellReuseIdentifier identifier: String)
Which is methods of UITableView
In your case probably something like this:
tb.register(ProfileActivitySubCell.classForCoder(), forCellReuseIdentifier: "tableCell")
1) Refactor the table view data source methods to a separate class
class IceCreamListDataSource: NSObject, UITableViewDataSource
{
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("IceCreamListCell", forIndexPath: indexPath)
return cell
}
}
2) In your controller class do this-:
class IceCreamListViewController: UITableViewController
{
let dataSource = IceCreamListDataSource()
// MARK: - View lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = dataSource
}
}
I managed to solve the issue. As the tableView was inside a collection view I had to use a storyboard object outlet. Finally inside the collection view cell I had to set the delegate and dataSource to the newly created object.
cell.tableView.dataSource = dataService
cell.tableView.delegate = dataService
I have created a slide out menu using Swift. I have done this many times before, but when I created it today, I get this error (see screenshot). It could just be a simple mistake I have made.
Here is the code, that I think is causing the problem:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel!.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel!.text = tableData[indexPath.row]
return cell
}
Screenshot:
UPDATE: I have tried removing override
Hope someone can help!
The method does not override any method of the superclass because the signature is wrong.
The correct signature is
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
All parameters are non-optional types.
And use also the recommended method
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier,
forIndexPath: indexPath)
which also returns always a non-optional type
Make sure that your class implements UITableViewDelegate and UITableViewDataSource.
class MyController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// All your methods here
}
You won't need override keyword unless any other superclass already implements those methods.
See this works for me
Just confirm UITableViewDelegate and UITableViewDataSource
Implement required methods
import UIKit
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let containArray = ["One","two","three","four","five"]
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Table view data source and delegate methods
//Number of rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return containArray.count
}
//Prepare Custom Cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let identifier = "simpleTextCell"
var cell: SimpleTextCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? SimpleTextCell
if cell == nil {
tableView.registerNib(UINib(nibName: "SimpleTextCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? SimpleTextCell
}
let dayName = containArray[indexPath.row]
cell.lblProductName.text = dayName
return cell
}
//Handle click
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("productListSegue", sender: self)
}
}
Try to removing "!", declaration for this function is:
func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
and make sure you have set delegate and datasource of tableview to "self"
This is a fairly simple question I think. I've separated my UITableView delegate / data sources into their own extensions
//MARK: - UITableView Data Source/Delegate
extension TweetsViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TweetCell
return cell
}
}
However in the view controller itself I need to set the tblView delegate
class TweetsViewController : UIViewController {
#IBOutlet weak var tblView: UITableView!
var fetchedResultsController : NSFetchedResultsController!
//MARK: View Management
override func viewDidLoad() {
super.viewDidLoad()
tblView.dataSource = self
}
}
However, since the view controller is nor conforming to the protocols but having the extensions handle them, then how do I explicitly set the datasource and delegate for the tableView? Thanks!
You can divide in a extension, as you can check in the apple documentation section about Extensions handling Protocols.
Here I have implement a minimum code doing what you ask, check it out.
import UIKit
class TableViewViewController: UIViewController {
#IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
}
}
extension TableViewViewController: UITableViewDelegate,UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.textLabel!.text = "it works"
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
In Swift 3 and above the table view datasource and delegate methods changed.
import UIKit
class HomeViewController: UIViewController {
#IBOutlet var tblPropertyList: UITableView!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tblPropertyList.delegate = self
tblPropertyList.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Table View DataSource
extension HomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
cell.textLabel!.text = "\(indexPath.row) - Its working"
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
}
// MARK: - Table View Delegate
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)!
print(currentCell.textLabel!.text!)
}
}
the view controller is nor conforming to the protocols but having the extensions handle them
This is incorrect. The extension makes the view controller conformant to the protocols, and the data source and delegate can be set as usual, e.g.: self.tableView.delegate = self
Now in Swift 5.1 you don't need to inherit UITableViewDelegate and UITableViewDataSource
extension HomeViewController {
// MARK: - Table View DataSource
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
cell.textLabel!.text = "\(indexPath.row) - Its working"
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
}
// MARK: - Table View Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)!
print(currentCell.textLabel!.text!)
}
}
I have asked this question once before however I feel like i haven't been as thorough as can be. I am attempting to complete a very standard drill down table view hierarchy programmatically rather than using the IB to avoid unnecessary scramble due to the fact i have well over 40 different views i want to implement. I have decided to use the following switch-statement:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var VC: UITableViewController
switch indexPath.row {
case 0: VC = SecondTableViewController()
default: ()
}
navigationController?.pushViewController(VC, animated: true)
}
as you can see it gives me the non-initialized error, so i then proceed to make my variable an optional to fix this issue & it compiles and runs:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var VC: UITableViewController?
switch indexPath.row {
case 0: VC = SecondTableViewController()
default: ()
}
navigationController?.pushViewController(VC!, animated: true)
}
however when i select the designated row (which is correct at the value of 0 after running under the debugger) it crashes with this error:
what seems to be the issue? is it the default statement within my switch? or is it the variable within my "pushViewController" method? Might i add, when i change the parameter within this method from "VC/VC!" to "UITableViewController()" like such:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var VC: UITableViewController?
switch indexPath.row {
case 0: VC = SecondTableViewController()
default: ()
}
navigationController?.pushViewController(UITableViewController, animated: true)
}
it runs & functions accordingly, but when the view is pushed, it is not to the TableViewController i designated in my switch statement, rather then just a blank table view. what am i missing?
HERE IS THE CODE FOR MY SecondTableViewController :
import UIKit
class SecondTableViewController: UITableViewController {
var myVariable = ["LIST OF STRINGS IN AN ARRAY"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myVariable.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
var superVariable = myVariable [indexPath.row]
cell.textLabel!.text = superVariable
return cell
}
}
The problem lies in SecondTableViewController where you didn't define an identifier for your cell. You should do something like this,
class SecondTableViewController: UITableViewController {
let theData = ["one", "two", "three", "four"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return theData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = theData[indexPath.row]
return cell
}
}