Samuel Patterson Samuel Patterson - 1 month ago 10
Swift Question

swift delegate showing nil

I have created a .xib and adding this xib to another view. I want to add a delegate method in that .xib file. Here is my code :

.xib file

import UIKit

protocol CustomCheckBoxWithCrossDelegate {

func deleteCustomCheckbox(itemToDelete: String)
}

class CustomCheckBoxWithCross: UIView {

@IBOutlet weak var radioButton: UIButton!
@IBOutlet weak var checkboxLbl: UILabel!
@IBOutlet weak var checkboxCrossBtn: UIButton!

var blockIndexForTheCrossButton: Int = 0
var delegate: CustomCheckBoxWithCrossDelegate!

override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib ()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib ()
}


func loadViewFromNib() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CustomCheckBoxWithCross", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(view);
}


@IBAction func crossBtnTapped(sender: AnyObject) {
print("Delegate --> \(delegate)")
delegate!.deleteCustomCheckbox("hello")
}
}



  • But in "crossBtnTapped" method I am getting nil value for that delegate.



can anyone please tell me what I am doing wrong?

Answer

You must have the instance of CustomCheckBoxWithCross in your other class, where you have implemented the protocol. Set delegate property of CustomCheckBoxWithCross instance to self in that file.

Comments