How to use delegates to communicate data from a custom cell to a label in the parent view - ios

I have figured out how to pass data between views with delegates in other situations but this one is stumping me.
In this example I am trying to send data resulting from pressing a button, up to the label using a delegate pattern but without any success. My guess is that I am missing something fundamental here and I haven't found any examples that deal with delegates in quite this way.
//
// ViewController.swift
// TableCellDelegate
//
// Created by Chris Cantley on 6/1/15.
// Copyright (c) 2015 Chris Cantley. All rights reserved.
//
import UIKit
class ViewController: UIViewController, CellInfoDelegate {
var cellViewController = CellViewController()
//The place to put the number into.
#IBOutlet weak var sumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
cellViewController.delegate = self
}
//2)...to here.
func processThatNumber(theNumber: Int) {
println("out : \(theNumber)")
}
}
// Table View delegates
extension ViewController: UITableViewDataSource, UITableViewDelegate
{
//One row
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// Load custom cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("thisCustomCell", forIndexPath: indexPath) as! CellViewController
return cell
}
}
//-------------------- Protocol for Delegate -----------------------
protocol CellInfoDelegate {
func processThatNumber(theNumber: Int)
}
//-------------------- Cell to Pass info to Parent -----------------------
class CellViewController: UITableViewCell{
var sumNumber: Int = 0
var delegate: CellInfoDelegate?
#IBAction func addButton(sender: AnyObject) {
// increment that number
self.sumNumber += 5
//1) I want to get it from here...... but delegate ends up nil
if let delegate = self.delegate {
delegate.processThatNumber(self.sumNumber)
}
//Shows that the number is incrementing
println(sumNumber)
}
}
The ViewController and CellViewController are connected to their respective classes
Thanks in advance.

You should set the delegate here:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("thisCustomCell", forIndexPath: indexPath) as! CellViewController
cell.delegate = self // <-- Set the delegate.
return cell
}

Thanks to i_am_jorf for the solution, here is the code that works.
//
// ViewController.swift
// TableCellDelegate
//
// Created by Chris Cantley on 6/1/15.
// Copyright (c) 2015 Chris Cantley. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, CellInfoDelegate {
//The place to put the number into.
#IBOutlet weak var sumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
//2)...to here.
func processThatNumber(theNumber: Int) {
println("out : \(theNumber)")
self.sumLabel.text = toString(theNumber) as String
}
}
// Table View delegates
extension ViewController: UITableViewDataSource, UITableViewDelegate
{
//One row
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// Load custom cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("thisCustomCell", forIndexPath: indexPath) as! CellViewController
//SOLUTION : put the Delgate HERE in the place where the cell is instantiated so that there is a connection back
// to this class from the Cell class
cell.delegate = self
return cell
}
}
//-------------------- Protocol for Delegate -----------------------
protocol CellInfoDelegate {
func processThatNumber(theNumber: Int)
}
//-------------------- Cell to Pass info to Parent -----------------------
class CellViewController: UITableViewCell{
var sumNumber: Int = 0
var delegate: CellInfoDelegate?
#IBAction func addButton(sender: AnyObject) {
// increment that number
self.sumNumber += 5
//1) I want to get it from here...... but delegate ends up nil
if let delegate = self.delegate {
delegate.processThatNumber(self.sumNumber)
}
//Shows that the number is incrementing
println(sumNumber)
}
}

Do you need to use Delegates?
What if you have this function output a number:
func processThatNumber(theNumber: Int) -> Int {
println("out : \(theNumber)")
return theNumber
}
Then set the text on the label using the button:
#IBAction func addButton(sender: AnyObject) {
self.sumNumber += 5
sumLabel.text = "\(processThatNumber(self.sumNumber))"
println(sumNumber)
}
Would that work for you?

Related

Table view cell elements not able to click and get data

I have one table view and inside that i placed one main view. And inside that main view i placed one button.And when ever use click on my cell button. I need to get the cell title label.This is what i need. But i tried following below code. Not sure what i am missing out. It not at all calling my cell.add target line.
Code in cell for row at index:
cell.cellBtn.tag = indexPath.row
cell.cellBtn.addTarget(self, action:#selector(self.buttonPressed(_:)), for:.touchUpInside)
#objc func buttonPressed(_ sender: AnyObject) {
print("cell tap")
let button = sender as? UIButton
let cell = button?.superview?.superview as? UITableViewCell
let indexPath = tableView.indexPath(for: cell!)
let currentCell = tableView.cellForRow(at: indexPath!)! as! KMTrainingTableViewCell
print(indexPath?.row)
print(currentCell.cellTitleLabel.text)
}
I even added a breakpoint, still it not at calling my cell.addTarget line
Tried with closure too. In cell for row at index:
cell.tapCallback = {
print(indexPath.row)
}
In my table view cell:
var tapCallback: (() -> Void)?
#IBAction func CellBtndidTap(_ sender: Any) {
print("Right button is tapped")
tapCallback?()
}
Here that print statement is getting print in console.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var list = [String]()
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
cell.saveButton.tag = indexPath.row
//cell.saveButton.accessibilityIdentifier = "some unique identifier"
cell.tapCallback = { tag in
print(tag)
}
return cell
}
}
class MyTableViewCell: UITableViewCell {
// MARK: - IBOutlets
#IBOutlet weak var saveButton: UIButton!
// MARK: - IBActions
#IBAction func saveTapped(_ sender: UIButton) {
tapCallback?(sender.tag)
}
// MARK: - Actions
var tapCallback: ((Int) -> Void)?
}
Actually this is not a good programming practice to add the button (which contains in table view cell) target action in view controller. We should follow the protocol oriented approach for it. Please try to under stand the concept.
/*This is my cell Delegate*/
protocol InfoCellDelegate {
func showItem(item:String)
}
/*This is my cell class*/
class InfoCell: UITableViewCell {
//make weak reference to avoid the Retain Cycle
fileprivate weak var delegate: InfoCellDelegate?
//Outlet for views
#IBOutlet var showButton: UIButton?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//This is the public binding function which will bind the data & delegate to cell
func bind(with: DataModel?, delegate: InfoCellDelegate?, indexPath: IndexPath) {
//Now the bind the cell with data here
//.....
//Assign the delegate
self.delegate = delegate
}
//Button action
#IBAction func rowSelected(sender: UIButton) {
self.delegate?.showItem(item: "This is coming from cell")
}
}
/*Now in your ViewController you need to just confirm the InfoCellDelegate & call the bind function*/
class ListViewController: UIViewController {
//Views initialisation & other initial process
}
//Table view Delegate & Data source
extension ListViewController: UITableViewDataSource, UITableViewDelegate {
/**
Configure the table views
*/
func configureTable() {
//for item table
self.listTable.register(UINib.init(nibName: "\(InfoCell.classForCoder())", bundle: nil), forCellReuseIdentifier: "\(InfoCell.classForCoder())")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
cell.bind(with: DataModel, delegate: self, indexPath: indexPath)
return cell
}
}
extension ListViewController: InfoCellDelegate {
func showItem(item) {
print(item)
}
}

When I go back to the page, changing number and cell datas of the TableView

I am using nested tableview. The main tableview lists the file categories. Child tableview listing the files. I open the files with safari. The child tableview is listed incorrectly when I go back to the page after opening the file. How can i solve this problem? Android sdk have "onActivityResult" method. Does iOS have a similar function? Thanks.
ViewController
import UIKit
class ProductDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
var bundleProductModel:ProductModel? = ProductModel.init()
var lastFileCatIndex:Int = 0
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// If tableview is file category table.
if (tableView.tag == 100){
return bundleProductModel!.fileCategoryModels.count
} else /* Table view is file tableview. */ {
//self.lastFileIndex = self.lastFileIndex + 1
return (bundleProductModel?.fileCategoryModels[self.lastFileCatIndex].files.count)!
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView.tag == 100){
// Define cell for file category.
let cell = tableView.dequeueReusableCell(withIdentifier: "FileCategoryTableViewCell") as! FileCategoryTableViewCell
// Set file category cell height.
cell.frame.size.height = CGFloat(((bundleProductModel?.fileCategoryModels[indexPath.row].files.count)! * 44) + 42)
// cell row height
tableView.rowHeight = CGFloat(((bundleProductModel?.fileCategoryModels[indexPath.row].files.count)! * 44) + 42)
// Control bound
if (self.lastFileCatIndex <= indexPath.row){
// Index.
self.lastFileCatIndex = indexPath.row
// File category name.
cell.lblFileCatNme.text = " \(bundleProductModel?.fileCategoryModels[indexPath.row].file_category_name ?? "Unknow") "
}
return cell
} else {
// Define cell for files.
let cell = tableView.dequeueReusableCell(withIdentifier: "FileTableViewCell") as! FileTableViewCell
if ((bundleProductModel?.fileCategoryModels[self.lastFileCatIndex].files.count)! > indexPath.row){
// Set file model to file cell.
cell.setFile(fileItem: (self.bundleProductModel?.fileCategoryModels[self.lastFileCatIndex].files[indexPath.row])!)
// file cell delegate
cell.delegate = self
} else {
cell.lblFileName.text = "unknow"
}
return cell
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ProductDetailViewController:FileCellDelegate{
func didClickDownload(downloadLink: String, button: UIButton) {
if let url = URL(string: downloadLink) {
UIApplication.shared.open(url)
}
}
}
A very easy workaround on iOS would be to override viewWillAppear and call reloadData() like so:
override func viewWillAppear() {
super.viewWillAppear()
tableView.reloadData()
}
This will update your table everytime your view reappears.
SOLVED
Problem is lastFileCategoryIndex variable. Ex: final value is four. When I come back to the page; listing relative to fourth index. I define child tableview in main tableview cell and solved.
FileCategoryTableViewCell
class FileCategoryTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
// General Objects
var fileCategoryModel:FileCategoryModel = FileCategoryModel.init()
// Cell Ui Objects
#IBOutlet weak var lblFileCatNme: UILabel!
#IBOutlet weak var fileTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fileCategoryModel.files.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = fileTableView.dequeueReusableCell(withIdentifier: "FileTableViewCell") as! FileTableViewCell
cell.lblFileName.text = "Ex File..."
return cell
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// Set category model.
func setFileCategory(fileCategoryModel:FileCategoryModel){
self.fileCategoryModel = fileCategoryModel
self.fileTableView.dataSource = self
self.fileTableView.delegate = self
}
}

Not using reusable cell in UITableView with CollectionView in each cell

I have a UITableView and in its prototype cell have a UICollectionView.
MainViewController is delegate for UITableView and
MyTableViewCell class is delegate for UICollectionView.
On updating each TableViewCell contents I call cell.reloadData() to make the collectionView inside the cell reloads its contents.
When I use reusable cells, as each cell appears, it has contents of the last cell disappeared!. Then it loads the correct contents from a URL.
I'll have 5 to 10 UITableViewCells at most. So I decided not to use reusable cells for UITableView.
I changed the cell creation line in tableView method to this:
let cell = MyTableViewCell(style: .default, reuseIdentifier:nil)
Then I got an error in MyTableViewCell class (which is delegate for UICollectionView), in this function:
override func layoutSubviews() {
myCollectionView.dataSource = self
}
EXC_BAD_INSTRUCTION CODE(code=EXC_I386_INVOP, subcode=0x0)
fatal error: unexpectedly found nil while unwrapping an Optional value
MyTableViewCell.swift
import UIKit
import Kingfisher
import Alamofire
class MyTableViewCell: UITableViewCell, UICollectionViewDataSource {
struct const {
struct api_url {
static let category_index = "http://example.com/api/get_category_index/";
static let category_posts = "http://example.com/api/get_category_posts/?category_id=";
}
}
#IBOutlet weak var categoryCollectionView: UICollectionView!
var category : IKCategory?
var posts : [IKPost] = []
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
if category != nil {
self.updateData()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
categoryCollectionView.dataSource = self
}
func updateData() {
if let id = category?.id! {
let url = const.api_url.category_posts + "\(id)"
Alamofire.request(url).responseObject { (response: DataResponse<IKPostResponse>) in
if let postResponse = response.result.value {
if let posts = postResponse.posts {
self.posts = posts
self.categoryCollectionView.reloadData()
}
}
}
}
}
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath as IndexPath) as! MyCollectionViewCell
let post = self.posts[indexPath.item]
cell.postThumb.kf.setImage(with: URL(string: post.thumbnail!))
cell.postTitle.text = post.title
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//You would get something like "model.count" here. It would depend on your data source
return self.posts.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
}
MainViewController.swift
import UIKit
import Alamofire
class MainViewController: UITableViewController {
struct const {
struct api_url {
static let category_index = "http://example.com/api/get_category_index/";
static let category_posts = "http://example.com/api/get_category_posts/?category_id=";
}
}
var categories : [IKCategory] = []
override func viewDidLoad() {
super.viewDidLoad()
self.updateData()
}
func updateData() {
Alamofire.request(const.api_url.category_index).responseObject { (response: DataResponse<IKCategoryResponse>) in
if let categoryResponse = response.result.value {
if let categories = categoryResponse.categories {
self.categories = categories
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return self.categories.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.categories[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionHolderTableViewCell") as! MyTableViewCell
let cell = MyTableViewCell(style: .default, reuseIdentifier:nil)
cell.category = self.categories[indexPath.section]
cell.updateData()
return cell
}
}
MyCollectionViewCell.swift
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var postThumb: UIImageView!
#IBOutlet weak var postTitle: UILabel!
var category : IKCategory?
}
Why not reusing cells caused this? Why am I doing wrong?
There are a few things to do that should get you up to speed.
First, uncomment the line that uses reusable cells and remove the line of code that creates the non-reusable cells. It is safe to use reusable cells here.
Second, in MyTableViewCell, set the dataSource for the collection view right after the super.awakeFromNib() call. You only need to set the dataSource once, but layoutSubviews() will potentially get called multiple times. It's not the right place to set the dataSource for your needs.
override func awakeFromNib() {
super.awakeFromNib()
categoryCollectionView.dataSource = self
}
I have removed the call to updateData() from awakeFromNib(), as you are already calling it at cell creation. You can also delete the layoutSubviews() override, but as a general rule, you should be careful to call super.layoutSubviews() when overriding it.
Lastly, the reason the posts seemed to re-appear in the wrong cells is that the posts array wasn't being emptied as the cells were reused. To fix this issue, add the following method to MyTableViewCell:
func resetCollectionView {
guard !posts.isEmpty else { return }
posts = []
categoryCollectionView.reloadData()
}
This method empties the array and reloads your collection view. Since there are no posts in the array now, the collection view will be empty until you call updateData again. Last step is to call that function in the cell's prepareForReuse method. Add the following to MyTableViewCell:
override func prepareForReuse() {
super.prepareForReuse()
resetCollectionView()
}
Let me know how it goes!

How to perform a segue view from custom UITableViewCell(xib) to another ViewController

I want to show a button on my custom UITableViewCell which takes the user to another screen on tapping on it.
I have tried following code but it doesn't work
Child view:
#IBAction func childScreenButton(sender: AnyObject) {
if let delegate = self.delegate {
delegate.childButtonClickedOnCell(self)
}
}
Protocol:
protocol childTableCellDelegate: class {
func childButtonClickedOnCell(cell: childViewCell)
}
Parent ViewController:
func childButtonClickedOnCell(cell: FeedChildViewCell) {
self.clickedIndexPath = self.feedsTableView.indexPathForCell(cell)
self.performSegueWithIdentifier("toNextScreen", sender: self)
}
while I'm testing the break point doesn't enter into "delegate.childButtonClickedOnCell(self)" on child view. Please let me know if am doing anything wrong here. Thanks!!
I suspect you've got a couple things out of place, or not defined just right.
I just ran a quick test with this, and the delegate call works fine... see if you notice anything not-quite-the-same...
//
// TestTableViewController.swift
//
// Created by DonMag on 4/7/17.
// Copyright © 2017 DonMag. All rights reserved.
//
import UIKit
protocol MyCellDelegate {
func pressedButtonForMyCell(theSender: MyCell)
}
class MyCell: UITableViewCell {
#IBOutlet weak var theLabel: UILabel!
#IBOutlet weak var theButton: UIButton!
var delegate: MyCellDelegate?
#IBAction func childScreenButton(sender: AnyObject) {
delegate?.pressedButtonForMyCell(theSender: self)
}
}
class TestTableViewController: UITableViewController, MyCellDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyCell
cell.theLabel.text = "\(indexPath)"
cell.delegate = self
return cell
}
func pressedButtonForMyCell(theSender: MyCell) {
print("delegate called", theSender)
}
}

appending array via swift 2

i have a problem with appending an array, you can see my code, i checked the problem's line by: self.items.append(....)
the array is not appended and stay empty.
here is my code:
//
// ViewController.swift
// firer
//
// Created by mike matta on 06/01/2016.
// Copyright © 2016 Mikha Matta. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var showdatA: UILabel!
#IBOutlet weak var tableView: UITableView!
var items:[String] = []
var userFNAME:String = ""
var userDOB:String = ""
let textCellIdentifier = "TextCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
///////////
let UsersChannel = Firebase(url: "https://MYFIREBASE.firebaseio.com/users")
UsersChannel.observeEventType(.ChildAdded, withBlock: { snapshot in
if let az = String?((snapshot.value.objectForKey("full_name"))! as! String) {
self.userFNAME = az
}
if let az2 = String?((snapshot.value.objectForKey("dob"))! as! String) {
self.userDOB = az2
}
print("\(self.userFNAME) - \(self.userDOB)")
self.items.append(self.userFNAME) // heeereeee what i am trying to doooooooo
})
// print(self.items)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell
let row = indexPath.row
cell.textLabel?.text = items[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(items[row])
}
}
i tryed to put the array definition inside the viewdidload() it works...but i need it outside it (like my code)..
i tryed to put the array outside the async block too...still not appending....any one ?
I think that your code works !
The question is :
Why do you think that your array is still empty ?
You have to think the order that your instructions are executed.
At this line :
// print(self.items);
Your array is still empty because the closure is not yet called.
Put this line just after the append and you will see.
And, Just add self.tableView.reloadData() after your append and you will be happy :)
(It will say to your tableview to recall the delegate methods (numberOfRowsInSection ...) )

Resources