Delegating action through protocol not working swift - ios

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.

Related

Instantiate the delegate pattern one time or more in Swift?

I am studying delegate pattern for swift on below code. I can not be pretty sure how can I use this option "without the need to reinstantiate the view.
protocol ShapeViewDelegate {
func drawShapeView(_ shapeView: ShapeView)
}
class ShapeView: UIView {
var strokeColor: UIColor?
var fillColor: UIColor?
var delegate: ShapeViewDelegate? {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
delegate?.drawShapeView(self) // self means object( ShapeView() ) is it instantiated ?
}
}
View object supposed to ready coming from delegate object but I didn't instantiate it, where this object instantiated using protocol automatically instantiated it at the run time. So I am writing an example like this :
class ShapeViewController: ShapeViewDelegate {
drawShapeView(view)
}
View is instantiated in other words occupied the memory at this example ?
You have to define drawShapeView() in ShapeViewController. In your code you are using or calling drawShapeView() which is already being called in your ShapeView. And about instantiate, yes you need to instantiate ShapeView in ShapeViewController or any other place you are confirming the delegate.
Code in your ShapeViewController -
class ShapeViewController: ShapeViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let shape = ShapeView(...)
shape.delegate = self
view.addSubView(shape)
}
func drawShapeView(_ shapeView: ShapeView) {
//your code here
}
}
Via this feature, you can have many definitions of ShapeView based on different ShapeViewController instances without worrying to modify ShapeView.

How to implement didTapCheckBox of BEMCheckBox IOS Library?

I am new in Ios and i am having hard time wrapping my head around protocols and delegates concept. I am implementing a library called BEMCheckBox https://github.com/Boris-Em/BEMCheckBox or https://cocoapods.org/pods/BEMCheckBox for implementing radio buttons. Its documentation is pretty descriptive using which i have successfully added checkboxes, grouped them together to work as radio boxes.
#IBOutlet var inarelashipcb: BEMCheckBox!
#IBOutlet var complicatedcb: BEMCheckBox!
#IBOutlet var singlecb: BEMCheckBox!
var groupbx:BEMCheckBoxGroup!
func initialize(){
groupbx = BEMCheckBoxGroup(checkBoxes: [inarelashipcb,
complicatedcb, singlecb])
groupbx.selectedCheckBox = singlecb
groupbx.mustHaveSelection = true
}
Now i want to use didTapCheckBox method but i donot understand how. The documentation is blurry there no snippets for that. For the record this is what the documentation states
"BEMCheckBox uses a delegate to receive check box events. The delegate object must conform to the BEMCheckBoxDelegate protocol, which is composed of two optional methods:
didTapCheckBox:
Sent to the delegate every time the check box gets tapped, after its properties are updated (on), but before the animations are completed."
Any snippets to help me use delgate so i can implement didTapCheckBox method?
func initialize(){
groupbx = BEMCheckBoxGroup(checkBoxes: [inarelashipcb,
complicatedcb, singlecb])
groupbx.selectedCheckBox = singlecb
groupbx.mustHaveSelection = true
for checkbox in groupbx {
checkbox.delegate = self
}
}
must call initialize in viewDidLoad of the viewController
override func viewDidLoad() {
// Do your work
initialize()
}
compiler will show you an error, error will be gone if you add this codes
extension ViewController : BEMCheckBoxDelegate {
func didTap(_ checkBox: BEMCheckBox) {
//do your work
// if you have multiple checkboxes, then do like that
//if checkBox == checkBox1 {
//do work for checkbox1
//} else if {
// ..
//}
}
}
Don't forget to add the following line
import BEMCheckBox
The outlet checkbox you have declared, set delegate to self.
For eg, if your checkbox outlet is checkbox1 set its delegate as
checkbox1.delegate = self
I solve it.
using this code
func initialize(){
groupbx = BEMCheckBoxGroup(checkBoxes: [inarelashipcb,
complicatedcb, singlecb])
groupbx.selectedCheckBox = singlecb
groupbx.mustHaveSelection = true
inarelashipcb.delegate = self
complicatedcb.delegate = self
singlecb.delegate = self
}
func didTap(_ checkBox: BEMCheckBox) {
print("here hello")
}
Also my uiviewcontroller inherited from BEMCheckBoxDelegate

Performing Segue from Another Class via a Function Without Storyboards

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.

How to use delegates properly in Swift?

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)
}
}

Passing data between views in ONE ViewController in Swift

All of the searches I've done focus on passing data between view controllers. That's not really what I'm trying to do. I have a ViewController that has multiple Views in it. The ViewController has a slider which works fine:
var throttleSetting = Float()
#IBAction func changeThrottleSetting(sender: UISlider)
{
throttleSetting = sender.value
}
Then, in one of the Views contained in that same ViewController, I have a basic line that (for now) sets an initial value which is used later in the DrawRect portion of the code:
var RPMPointerAngle: CGFloat {
var angle: CGFloat = 2.0
return angle
}
What I want to do is have the slider's value from the ViewController be passed to the View contained in the ViewController to allow the drawRect to be dynamic.
Thanks for your help!
EDIT: Sorry, when I created this answer I was having ViewControllers in mind. A much easier way would be to create a method in SomeView and talk directly to it.
Example:
class MainViewController: UIViewController {
var view1: SomeView!
var view2: SomeView!
override func viewDidLoad() {
super.viewDidLoad()
// Create the views here
view1 = SomeView()
view2 = SomeView()
view.addSubview(view1)
view.addSubview(view2)
}
#IBAction func someAction(sender: UIButton) {
view1.changeString("blabla")
}
}
class SomeView: UIView {
var someString: String?
func changeString(someText: String) {
someString = someText
}
}
Delegate:
First you create a protocol:
protocol NameOfDelegate: class { // ": class" isn't mandatory, but it is when you want to set the delegate property to weak
func someFunction() // this function has to be implemented in your MainViewController so it can access the properties and other methods in there
}
In your Views you have to add:
class SomeView: UIView, NameOfDelegate {
// your code
func someFunction() {
// change your slider settings
}
}
And the last step, you'll have to add a property of the delegate, so you can "talk" to it. Personally I imagine this property to be a gate of some sort, between the two classes so they can talk to each other.
class MainViewController: UIViewController {
weak var delegate: NameOfDelegate?
#IBAction func button(sender: UIButton) {
if delegate != nil {
let someString = delegate.someFunction()
}
}
}
I used a button here just to show how you could use the delegate. Just replace it with your slider to change the properties of your Views
EDIT: One thing I forgot to mention is, you'll somehow need to assign SomeView as the delegate. But like I said, I don't know how you're creating the views etc so I can't help you with that.
In the MVC model views can't communicate directly with each other.
There is always a view controller who manages the views. The views are just like the controllers minions.
All communication goes via a view controller.
If you want to react to some view changing, you can setup an IBAction. In the method you can then change your other view to which you might have an IBOutlet.
So in your example you might have an IBAction for the slider changing it's value (as in your original question) from which you could set some public properties on the view you would like to change. If necessary you could also call setNeedsDisplay() on the target view to make it redraw itself.

Resources