I have a Social Network Feed in form UItableView which has a cell. Now each cell has an image that animates when an even is triggered. Now, This event is in form of a string, will be triggered at every cell. the options for the event are defined in another class(of type NSObject).
My issue:
I constructed a protocol delegate method in table view, which will be called whenever the event is triggered for each cell. Then, I define this function in UITableViewCell Class, since my the image will be animating on that.
All is working well but I am unable to figure out how to assign the delegate of TableView class to cell class. What I mean is, how can I use UITableView.delegate = self in cellView class. I have tried using a static variable, but it doesn't work.
I have been playing around the protocols for a while now but really unable to figure out a solution to this.
I hope I am clear. If not, I will provide with an example in the comments. I am sorry, This is a confidential project and I cant reveal all details.
If I understand you correctly, you are trying to make each of your cells conform to a protocol that belongs to their UITableView? If this is the case then this cannot be done. The Delegation design pattern is a one to one relationship, i.e only one of your UITableViewCells would be able to conform to the UITableView's delegate.
Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.
Quote from the Apple Docs
I would suggest that your UITableViewCell should call a block (Objective-C) or a closure (Swift) whenever your specified event is triggered to achieve what you are looking for. Set up this closure in your tableView:cellForRowAtIndexPath function.
EXAMPLE
TableViewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCellID", for: indexPath) as! MyTableViewCell
cell.eventClosure = {
//Do something once the event has been triggered.
}
return cell
}
TableViewCell
func eventTriggered()
{
//Call the closure now we have a triggered event.
eventClosure()
}
If I correctly understood your question, maybe this could help:
class ViewController: UIViewController, YourCustomTableDelegate {
#IBOutlet weak var tableView: YourCustomTableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.customTableDelegate = self
}
// table delegate method
func shouldAnimateCell(at indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.animate(...)
}
}
}
Try something like this:
Define your delegate protocol:
protocol CustomCellDelegate: class {
func animationStarted()
func animationFinished()
}
Define your CustomCell. Extremely important to define a weak delegate reference, so your classes won't retain each other.
class CustomCell: UITableViewCell {
// Don't unwrap in case the cell is enqueued!
weak var delegate: CustomCellDelegate?
/* Some initialization of the cell */
func performAnimation() {
delegate?.animationStarted()
UIView.animate(withDuration: 0.5, animations: {
/* Do some cool animation */
}) { finished in
self.delegate?.animationFinished()
}
}
}
Define your view controller. assign delegate inside tableView:cellForRowAt.
class ViewController: UITableViewDelegate, UITableViewDataSource {
/* Some view controller customization */
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: CustomCell.self)) as? CustomCell
cell.delegate = self
cell.performAnimation()
return cell
}
}
Related
Albeit potentially subjective, I was wondering how to go about having a custom UICollectionViewCell that when its UIButton is pressed, informs a custom UICollectionViewController of what to do.
My first thought was use a delegate in the CustomCell as follows:
class CustomCell: UICollectionViewCell {
var delegate: CustomCellDelegate?
static let reuseIdentifier = "CustomCell"
#IBOutlet weak private var button: UIButton! {
didSet {
button.addTarget(self, action: #selector(self.toggleButton), for: .touchUpInside)
}
}
#objc private func toggleButton() {
delegate?.didToggleButton()
}
}
where the class protocol for CustomCellDelegate is defined as:
protocol CustomCellDelegate: class {
func didToggleButton()
}
The UICollectionViewController then implements the didToggleButton function and assigns itself as the delegate to each cell as follows:
class CustomCollectionViewController: UICollectionViewController, CustomCellDelegate {
func didToggleButton() {
// do some stuff and then update the cells accordingly ...
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCell.reuseIdentifier, for: indexPath) as? CustomCell else { fatalError("Unexpected indexPath") }
customCell.delegate = self
return customCell
}
}
Is this the correct way to go about this, or is there another way to to communicate between a UICollectionViewCell and its parent controller?
Thanks for any suggestions.
Yes, it's the right solution for sure. Your custom cells are blind and they don't know anything about your controller. They only fire delegate methods.
But, there is one more right solution and it's observation. Somebody prefers delegation, somebody prefers observation. You can use NotificationCenter to post your notifications about touches happening in your cells and make your controller an observer which reacts to these notifications.
// inside your cell
NotificationCenter.default.post(name: Notification.Name("ButtonPressed"), object: nil)
// inside your controller
NotificationCenter.default.addObserver(self, selector: #selector(someHandler), name: Notification.Name("ButtonPressed"), object: nil)
And your func someHandler() will handle the call when your controller (observer) catches posted events.
Also, there is KVO, but it's messy and isn't good for that particular case since you have multiple cells.
One more way to setup communication channel is binding. It can be both manually written or reactive (e.g., using ReactiveSwift).
For example, manual one:
// in your controller
cell.pressHandler = {
// do something
...
}
// in your cell
var pressHandler: (() -> Void)?
...
// when the button is pressed you execute that handler
pressHandler?()
Yes, delegation is optimal when a communication has to be done to only one object. In this case the parent UICollectionViewController
Other methods of communications are-
Notification: When we want to communicate multiple objects post a notification.
KVO: To know when a value/property has changed. But use carefully.
I have one view controller named TableViewController and another customised cell called feed.swift
The cells are getting reused properly and I have put tags on various buttons as I wan't to know what button of what feed is pressed on.
In my cellForRowAtIndexPath I'm populating my username with json that I have parsed. It looks like this
cell.username.text = username[indexPath.row]
output-> ["andre gomes", "renato sanchez", "renato sanchez"]
Then I have tagged my username button like this
cell.usernamePress.tag = indexPath.row
This is going on in my TableViewController
In my feed.swift I'm checking if a button is pressed and printing out the tag assigned to that button
#IBAction func usernameBut(sender: AnyObject) {
print(usernamePress.tag)
}
output-> 2
Now I need to access the username array of TableViewController in feed.swift and do something like username[usernamePress.tag]
I tried making a global.swift file but I'm not able to configure it for an array of strings.
import Foundation
class Main {
var name:String
init(name:String) {
self.name = name
}
}
var mainInstance = Main(name: "hello")
Even after doing this I tried printing mainInstance.name and it returned hello even after changing it. I want a solution where the array of strings holds the values I set in TableViewController and I can be able to use them in feed.swift
Any suggestions would be welcome! I'm sorry if there are any similar question regarding this but I'm not able to figure out how to use it for a mutable array of strings
I suggest you don't use the array directly in your FeedCell but instead return the press-event back to your TableViewController where you handle the event. According to the MVC Scheme, which is the one Apple requests you to use (checkout Apples documentation), all your data-manipulation should happen in the Controller, which then prepares the Views using this data. It is not the View that is in charge to display the right values.
To solve your problem I would choose to pass back the press-event via the delegation-pattern, e.g. you create a FeedCellDelegate protocol that defines a function to be called when the button is pressed:
protocol FeedCellDelegate {
func feedCell(didPressButton button: UIButton, inCell cell: FeedCell)
}
Inside your FeedCell you then add a delegate property, which is informed about the event by the View:
class FeedCell {
var delegate: FeedCellDelegate?
...
#IBAction func pressedUsernameButton(sender: UIButton) {
delegate?.feedCell(didPressButton: sender, inCell: self)
}
}
If your TableViewController then conforms to the just defined protocol (implements the method defined in there) and you assign the ViewController as the View's delegate, you can handle the logic in the Controller:
class TableViewController: UITableViewController, FeedCellDelegate {
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FeedCell", forIndexPath: indexPath) as! FeedCell
cell.delegate = self
// Further setup
return cell
}
func feedCell(didPressButton button: UIButton, inCell cell: FeedCell) {
guard let indexPath = tableView.indexPathForCell(cell) else { return }
// Do your event-handling
switch (button.tag) {
case 2: print("Is username button")
default: print("Press not handled")
}
}
}
As you might recognize I changed your class name. A Feed sounds more like a Model-class whereas FeedCell implies its role to display data. It makes a programmer's life way easier if you choose self-explaining names for your classes and variables, so feel free to adapt that. :)
you should add a weak array property to the tableViewCell:
weak var userNameArray:[String]?
Then in your tableViewController pass the username array into the cell:
fun tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create the cell, then...
if let array = self.username {
cell.userNameArray = array
}
}
Then you can use the array in the cell itself to populate its fields handle button taps, etc.
My table view allows multiple cell selection, where each cell sets itself as selected when a button inside the cell has been clicked (similar to what the gmail app does, see picture below). I am looking for a way to let the UITableViewController know that cells have been selected or deselected, in order to manually change the UINavigationItem. I was hoping there is a way to do this by using the delegate methods, but I cannot seem to find one. didSelectRowAtIndexPath is handling clicks on the cell itself, and should not affect the cell's selected state.
The most straight forward way to do this would be to create our own delegate protocol for your cell, that your UITableViewController would adopt. When you dequeue your cell, you would also set a delegate property on the cell to the UITableViewController instance. Then the cell can invoke the methods in your protocol to inform the UITableViewController of actions that are occurring and it can update other state as necessary. Here's some example code to give the idea (note that I did not run this by the compiler, so there may be typos):
protocol ArticleCellDelegate {
func articleCellDidBecomeSelected(articleCell: ArticleCell)
func articleCellDidBecomeUnselected(articleCell: ArticleCell)
}
class ArticleCell: UICollectionViewCell {
#IBAction private func select(sender: AnyObject) {
articleSelected = !articleSelected
// Other work
if articleSelected {
delegate?.articleCellDidBecomeSelected(self)
}
else {
delegate?.articleCellDidBecomeUnselected(self)
}
}
var articleSelected = false
weak var delegate: ArticleCellDelegate?
}
class ArticleTableViewController: UITableViewController, ArticleCellDelegate {
func articleCellDidBecomeSelected(articleCell: ArticleCell) {
// Update state as appropriate
}
func articleCellDidBecomeUnselected(articleCell: ArticleCell) {
// Update state as appropriate
}
// Other methods ...
override tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueCellWithIdentifier("ArticleCell", forIndexPath: indexPath) as! ArticleCell
cell.delegate = self
// Other configuration
return cell
}
}
I would have a function like 'cellButtomDidSelect' in the view controller and in 'cellForRowAtIndexPath', set target-action to the above mentioned function
I have a UISwitch in each of my dynamically created rows of which I want to bind an NSIndexPath to an addTarget selector.
I had considered allowing the user to tap the row to toggle the switch, but from a UX perspective it makes more sense to have the switch handle this method, therefore using didSelectRowAtIndexPath is not an appropriate solution.
When my cell is created I currently bind a selector like this:
// Create listener for each switch
prefCell.subscribed?.addTarget(self,
action: "switchFlipped:",
forControlEvents: UIControlEvents.ValueChanged)
Which calls the corresponding method:
func switchFlipped(flipSwitch: UISwitch, indexPath: NSIndexPath) {}
Obviously this throws an error because NSIndexPath isn't a valid reference, as I believe it will only send the buttons reference. Is there any way I can bind the index path? If not, is there any way to get the current cell from the context of the UISwitch?
The target-action pattern does not allow arbitrary selectors. You can have f(sender:) and f(sender:event:). Both won't help you. But you can use code to figure out the indexPath in the function.
Code should be self explanatory:
func switchFlipped(flipSwitch: UISwitch) {
let switchOriginInTableView = flipSwitch.convertPoint(CGPointZero, toView: tableView)
if let indexPath = tableView.indexPathForRowAtPoint(switchOriginInTableView) {
println("flipped switched at \(indexPath)")
}
else {
// this should not happen
}
}
This should be the a good solution, not depending on a point. You call the superviews of the Switch and therefore calculate the index path of the cell.
func switchTapped(sender: UISwitch) -> NSIndexPath {
let cell = sender.superview!.superview! as UITableViewCell
return tableView.indexPathForCell(cell)!
}
This reliably works, that's why you can simply unwrap any optionals.
You can try 3 approaches, as you see fit.
Create a custom UISwitch class and add an NSIndexPath property to it. When you receive notification, type cast to your custom class and access the NSIndexPath.
Create a custom UITableViewCell class and save NSIndexPath to it. When you get notified of UISwitch, get its superviews and see which one is your customUITableViewCell instance and get the property.
If you only have one section, it means all you need to worry about are rows. Set the UISwitch tag as the row number and access it when switch is flipped.
The Most Tech-Savy Solution Use Extensions of Swift.
Extensions add new functionality to an existing class, structure, or enumeration type. This includes the ability to extend types for which you do not have access to the original source code
Apple Docs
Use delegation.
Your switch's target action should be a method in your custom UITableViewCell. That custom tableviewcell should declare a protocol and the tableview should be it's delegate. Then your tableviewcell should call its delegate method from within the switch's target function.
The delegate method for your tableviewcell should have a parameter in which the cell passes self. Then in your tableviewcontroller delegate implementation you can use indexPathForCell:
UPDATE:
Here is the apple doc for swift protocols and delegates:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html
Simply put, you need to define a protocol
protocol CustomUITableViewCellDelegate {
func tableViewCellSubscribed(cell: myCustomUITableViewCell) -> Void
}
then you make your tableviewcontroller class conform to that protocol like this:
class myTableViewController: UITableViewController, CustomUITableViewCellDelegate {
func tableViewCellSubscribed(cell: myCustomUITableViewCell) -> Void {
//this is where you handle whatever operations you want to do regarding the switch being valuechanged
}
// class definition goes here
}
Then your custom UITableViewCell class should have a delegate property like this:
class myCustomUITableViewCell : UITableViewCell {
var delegate : CustomUITableViewCellDelegate?
//class definition goes here
}
Finally, set the cell's delegate in tableView:cellForRowAtIndexPath: and you're good to go. You just need to call your tableViewCellSubscribed: delegate function from within the target method of your switch action.
I've used this approach in many projects, you can just add a callback to your custom cell, each time your switch changes, you can run this callback and catch it inside your table datasource implementation, below a dirt and simple example.
1. Create a UITableViewCell custom class
// An example of custom UITableViewCell class
class CustomCell:UITableViewCell {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var onSwitchChange:() -> Void?
}
class TableDataSource:UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as CustomCell
cell.onSwitchChange = {
NSLog("Table: \(tableView) Cell:\(cell) Index Path: \(indexPath)")
}
}
}
Acctually,Apple has already provide API to get the indexPath.
Simply like this (in Objective-C)
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Far easier, you can use the tag variable for this :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.mySwitch.tag = indexPath.item
cell.mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)
...
}
func switchChanged(mySwitch: UISwitch) {
let indexPathItem = mySwitch.tag
...
}
From official doc :
var tag: Int { get set }
An integer that you can use to identify view objects in your
application.
The default value is 0. You can set the value of this tag
and use that value to identify the view later.
When I use the UITableViewController to create a tableView, you get a lot of override functions, but when you use a regular UIViewController you get an error when using these same override functions and you are forced to change them to regular functions. I believe this is why my core data won't load into my cells, and tried to use the viewDidLoad function to get my data to load.
I know my code should work since all I'm trying to do is transfer all my code from a UITableViewController to a UIViewController, and my code worked in my UITableViewController.
My effort so far:
override func viewDidLoad() {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let CellID:NSString = "CELL"
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell
if let ip = indexPath as Optional {
var data:NSManagedObject = myList[ip.row] as NSManagedObject
cell.textLabel!.text = data.valueForKeyPath("username") as? String
}
return cell
}
}
Are the override functions the reason my cells are empty, or are there other aspects when using a regular UIViewController to show a tableView?
Any suggestions would be appreciated.
(1) You have to add UITableViewDelegate to the class in order to access the delegate methods, ex:
class ViewController: UIViewController, UITableViewDelegate {
After adding the UITableViewDelegate to the class, your UITableView delegate functions should auto-complete.
Also, make sure to set the UITableView's delegate to self in order to have the delegate methods populate the table.
(2) Right now, your cellForRowAtIndexPath method is within your viewDidLoad. Move it so it's not contained within any other method.