I am trying to perform a segue from another class via a class function.
I have a class called MyTableViewController. In that class I have constructed a view controller of the type AnswerViewController. A segue to this view controller is supposed to occur when a condition in the Extension : MyCell is met. The problem that I am having is that the function showNextView is not being called.
I have read posts on both Perform Segue From Another Swift File via a class function and Perform Segue from another class with helper function, but both of these create a segue before constructing the view controller (which I cannot do because I am not using storyboards and do not actually have segues, only pushViewController).
class MyTableViewController: UITableViewController {
//Construct View Controller
let answerViewController = AnswerViewController()
//Create goToNextView function which will be called in extension MyCell
func goToNextView(){
navigationController?.pushViewController(answerViewController, animated: true)
}
}
extension MyCell: YSSegmentedControlDelegate{
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
tagToIndex[actionButton.tag] = index
print(tagToIndex)
//Condition To Be Met
if tagToIndex == [0:1,1:0,2:1]{
//Access function goToNextView from MyTableViewController
func showNextView(fromViewController : MyTableViewController){
fromViewController.goToNextView()
}
}
}
}
How do I call the showNextView function so that the segue occurs?
Thanks,
Nick
You can't do this that way. Your showNextView function is nested inside segmentedControl(_, willPressItemAt) - this means it is not accessible outside of it. You generally shouldn't use nested functions.
To solve your issue you should create a delegate for your cell and inform your view controller that an action has occured.
A simple example :
protocol MyCellDelegate: class {
func myCellRequestedToOpenAnswerVC(cell: MyCell)
}
class MyCell {
weak var delegate: MyCellDelegate?
// rest of your inplementation
}
Then, change segmentedControl(_, willPressItemAt) to :
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
tagToIndex[actionButton.tag] = index
print(tagToIndex)
//Condition To Be Met
if tagToIndex == [0:1,1:0,2:1]{
self.delegate?.myCellRequestedToOpenAnswerVC(cell: self)
}
}
The last part happens in MyTableViewController - first, in your cellForRow method assign the view controller as delegate, something like this - cell.delegate = self, and make the view controller conform to MyCellDelegate:
extension MyTableViewController: MyCellDelegate {
func myCellRequestedToOpenAnswerVC(cell: MyCell) {
self.goToNextView()
}
}
Now, whenever the condition is met, your view controller will get informed about it and be able to act accordingly.
If you are not familiar with protocols and delegation pattern, I highly recommend reading through the docs, as it is something used extensively in CocoaTouch.
Related
I needed to delegate a click action for my UIView class to my UIViewController class since Swift does not support multiple class inheritance. So i wanted it such that once a button is clicked on my subview, a function in my BrowserViewController class is called.
I am using a protocol to achieve this, but on the function does not triggered when the button is tapped. Please help me out.
View Controller
class BrowseViewController: UIViewController {
var categoryItem: CategoryItem! = CategoryItem() //Category Item
private func setupExplore() {
//assign delegate of category item to controller
self.categoryItem.delegate = self
}
}
// delegate function to be called
extension BrowseViewController: ExploreDelegate {
func categoryClicked(category: ProductCategory) {
print("clicked")
let categoryView = ProductByCategoryView()
categoryView.category = category
categoryView.modalPresentationStyle = .overCurrentContext
self.navigationController?.pushViewController(categoryView, animated: true)
}
}
Explore.swift (subview)
import UIKit
protocol ExploreDelegate: UIViewController {
func categoryClicked(category: ProductCategory)
}
class Explore: UIView {
var delegate: ExploreDelegate?
class CategoryItem: UIView {
var delegate: ExploreDelegate?
var category: ProductCategory? {
didSet {
self.configure()
}
}
var tapped: ((_ category: ProductCategory?) -> Void)?
func configure() {
self.layer.cornerRadius = 6
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.categoryTapped)))
self.layoutIfNeeded()
}
#objc func categoryTapped(_ sender: UIGestureRecognizer) {
delegate?.categoryClicked(category: ProductCategory.everything)
self.tapped?(self.category)
}
}
}
Simply add a print statement inside categoryTapped.
You will then know if it is actually being tapped.
A million things could go wrong, for example, you may have forget to set the UIView to allow intertaction.
After checking that. Next add another print statement inside categoryTapped which shows you whether or not the delegate variable is null.
You'll quickly discover the problem using simple print statements.
print("I got to here!")
It's that easy.
And what about
if delegate == nil { print("it is nil!! oh no!" }
else { print("phew. it is NOT nil.") }
Debugging is really that easy at this level.
Next add a print statement inside setupExplore()
func setupExplore() {
print("setup explore was called")
....
See what happens.
I don't see any piece of code which sets the delegate.
First of all, define delegate as a property inside CategoryItem class, Then you must set the current instance of BrowseViewController to the delegate variable of CategoryItem. Now you can expect your method being called.
There are a few things that could cause the delegate method to not be triggered in this code:
Ensure that isUserInteractionEnabled = true on your CategoryItem. This is probably best done in either the configure() function in the CategoryItem or in the setupExplore() function of the BrowseViewController.
Make sure that the setupExplore() function on the BrowseViewController is being called, and that the category is being set on the CategoryItem to trigger the configure function. Otherwise, either the delegate or the gesture recognizer might not being set.
Side Note - weak vs strong delegate
On a side note, it is usually best practice to make your delegate properties weak var rather that having them be a strong reference, as this makes them prone to strong retain cycles.
Therefore, you might want to consider making the var delegate: ExploreDelegate? on your CategoryItem into weak var delegate: ExploreDelegate?. For more information on this problem, view this post.
So I have TableViewCell's that are being populated from 2 Dicitionaries in my view controller.
var categories : [Int : [String : Any]]!
var assignments : [Int: [String : Any]]!
I have a UiTextField in my cell that the user is supposed to be able to edit. I then want to be able to change the values of certain keys in that dictionary-based off what the user changes and re-display the table with those changes. My main problem is that I don't know how I will be able to access theese variables from within my cell. I have a method in my view controller that takes the row that the text field is in, along with the value of the textField, and updates the dictionaries. What I need is to be able to instantiate the view controller that the cell is in but I need the original instance that already has values loaded into the categories and assignments Dictionaries. If you have any other ideas on how I could accomplish this please post.
You can use delegate for sharing cell-data to your VC:
protocol YourCellDelegate() {
func pickedString(str: String)
}
class YourCell: UITableViewCell {
var delegate: YourCellDelegate! = nil
#IBOutlet weak var textField: UITextField!
.....//some set-method, where you can handle a text
func textHandle() {
guard let del = delegate else { return }
del.pickedString(textField.text)
}
.....
}
And usage in your VC: When you create cell, set its delegate self:
...
cell.delegate = self
...
and sure you VC supported your Delegate Protocol:
class YourVC: UIViewController, YourCellDelegate {
}
And now, you MUST implement protocol method:
class YourVC: UIViewController, YourCellDelegate {
....
func pickedString(str: String) {
}
....
}
All times, when you use textHandle() in your cell, pickedString(str: String) activates in yourVC with string from textField.
Enjoy!
I read a lot about the delegates but in practice I cannot use it properly.
Description: I have A: UIViewController, B: UIView, C: UIViewController. I want to run segue from A: UIViewController to the C: UIViewController from the inside of B: UIView.
I've tried:
protocol SegueDelegate {
func runSegue(identifier: String)
}
class B: UIView { ... }
where in my A: UIViewController:
override func viewDidLoad() {
B().delegate = self
}
func runSegue(identifier: String) {
self.performSegueWithIdentifier(identifier, sender: self)
}
and trying to call it via:
#IBAction func send(sender: AnyObject) {
let a: SegueDelegate? = nil
a!.runSegue("goToMainPage")
}
but I'm sure that I do not use it properly. Can anyone help me with it? I do not want just an answer. Please describe me it concept shortly
Delegates are just a Design Pattern that you can use in a number of ways. You can look at the Apple Frameworks to see how and where to use delegates as examples. A table view delegate is probably the best known delegate in UIKit.
Delegates serve as a callback mechanism for code to communicate with an instance of an unknown class without knowing more than that that instance will respond to the methods of the delegate protocol.
An alternative to a delegate is to use a closure (what we used to call a block in Objective-C). When to use one vs. the other is a matter of taste. There are a couple of rules of thumb, like for instance outlined here.
What you are doing is, IMO, the proper way to use delegates. You separate the view functionality from the View Controller's functionalities via a delegate, and so the contract for your view is clear: the user needs to respond to the delegate method.
Your code works and is correct. I made a quick implementation here: https://github.com/kristofvanlandschoot/DelegateUsage/tree/master
The main difference from your example, and maybe that's the place where you made a mistake is the third part of your code where you should write something like:
#IBAction func send(sender: AnyObject) {
delegate?.runSegue("segueAB")
}
There are multiple errors in your code, for example:
Here you are creating a new B, and setting A as a delegate of that new instance, no the one you actually want
override func viewDidLoad() {
«B()».delegate = self
}
And here you are creating force unwrapping a nil value
#IBAction func send(sender: AnyObject) {
let a: SegueDelegate? = «nil»
«a!».runSegue("goToMainPage")
}
If what you want to do is tell A to perform a segue to C, from inside B, all you need to do is to call performSegueWithIdentifier on A
For example:
class B: UIView {
weak var referenceToA: UIViewController? = nil // set this somewhere
#IBAction func send(sender: AnyObject) {
guard let a = referenceToA else {
fatalError("you didn't set the reference to a view controller of class A")
}
a.performSegueWithIdentifier("goToMainPage", sender: self)
}
}
I have an UIViewController
class WelcomeViewController: UIViewController
and an UIView
class SignUpView: UIView
Now I want to set in my WelcomeViewController delegate of SignUpView:
protocol SegueDelegate {
func runSegue(identifier: String)
}
class SignUpView: UIView { ... }
and connect it in
class WelcomeViewController: UIViewController, SegueDelegate {
how can I set in my WelcomeViiewController those delegate? When I'm trying to set:
override func viewDidLoad() {
SignUpView.delegate = self
}
it returns me
Instance member 'delegate' cannot be used on type 'SignUpView'
how can I find a solution?
You are trying to set delegate to a class. It should be an instance of the class i.e
let signUpView = SignUpView()
signUpView.delegate = self
What would be the point in doing that? If you want to navigate from one View to another, just add that Segue in Storyboard with an Identifier, so you can call self.performSegueWithIdentifier("IdentifierOfSegue", sender: self)
Create a weak property in SignUpView of that delegate(protocol) and name it other than delegate
then you can set and use it.
I agree with the developers saying "you can just do that via segue" but
the problem is you didn't declare a delegate var in the SignUpView class
so you can implement it in the signIn , if you declared it please write the line of code for me in a comment to check it
for now ...
I can suggest that you make a subview to be a parent class then override
which method you want to call
and you need to declare the delegate var as an optional (so you won't have
a memory cycle) like the following line ...
var delegate: SegueDelegate?
Let's solve this for people in need whom could need a solution when reading this issue:
In your UIView:
class SignUpView: UIView
you need to add:
var delegate : SegueDelegate?
Now, still in your class SignUpView, you need to add the function you want to delegate, just like this:
func runSegue(identifier: String) {
delegate?.runSegue(identifier)
}
This will call your delegate:
protocol SegueDelegate {
func runSegue(identifier: String)
}
Now, in your ViewController, you should have your SignUpView somewhere (created programmatically or linked through Storyboard / XIB).
In your viewDidLoadfunction, add: signUpView.delegate = self.
Don't forget to add SegueDelegatein your class heritage.
All,
I have set up a protocol, and the view controller is the delegate of this protocol, like so :
import Foundation
protocol PayButtonProtocol {
func enablePayButton()
func disablePayButton()
}
And the view controller is the delegate :
class ViewController: UIViewController, PayButtonProtocol
The protocol functions are as follows :
func enablePayButton() {
println("Button enabled")
PAYBarButton.enabled = false
}
func disablePayButton() {
PAYBarButton.enabled = false
}
I set a class and assign the delegate :
class Trigger
{
var delegate:PayButtonProtocol?
func EnablePayButton()
{
delegate?.enablePayButton()
}
}
Then I set the trigger to run the function :
let localtrigger = Trigger()
localtrigger.delegate = ViewController()
localtrigger.EnablePayButton()
This works and the 'button enabled' is displayed in the console. But the Bar Button (PAYBarButton) is nil and it seems that the view controller has lost its hieracy as I cannot access any of the view controllers objects. The View Controller was built with interface builder. Anyone got any ideas ? Is it
localtrigger.delegate = ViewController()
that rebuilds the viewconotroller and makes the original one not accessible ? If so how do i do this ?
if you are creating the localTrigger object inside your ViewController class you can just do:
let localtrigger = Trigger()
localtrigger.delegate = self // self is an instance of ViewController
localtrigger.EnablePayButton()