Samuel Patterson Samuel Patterson - 7 months ago 55
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]

@IBAction func crossBtnTapped(sender: AnyObject) {
print("Delegate --> \(delegate)")

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

can anyone please tell me what I am doing wrong?


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.