Jerry  Xu
Jerry Xu

Reputation: 295

Delegate between a view controller and a class

I want to set up a delegate to communicate between a view controller and a class. But there's nowhere to assign the delegate because there's not a prepareForSegue type of connection. Where should I put the delegate and how should I implement the code?

Here is the code:

Protocol in Swift:

@objc public protocol translationMadeDelegate: class {
    func didGetTranslation(translation:CGPoint)
}

Delegate initialization in viewDidLoad in Swift:

var delegate:translationMadeDelegate?
let trans:CGPoint = CGPointMake(100, 100)
self.delegate!.didGetTranslation(trans)

Objective-C class delegate call

- (void)didGetTranslation:(CGPoint *)translation {
    NSLog(@"cgpointed");
}

Upvotes: 1

Views: 1233

Answers (2)

kamwysoc
kamwysoc

Reputation: 6859

Take a look at this snippet of code it presents how the implementation should go

//Class

protocol translationMadeDelegate: class {
     func didGetTranslation(translation : CGPoint)
}

class someClass {
    weak var delegate: childViewControllerDelegate?

    func someMethodThatCallsDelegate(){
        let point = CGPoint(x: 10, y: 20)
        self.delegate?.didGetTranslation(point);
    }
}


//ViewController

class parentViewController: UIViewController, translationMadeDelegate {
    var classObj : someClass!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.classObj = someClass()
        self.classObj.delegate = self
    }
    func didGetTranslation(translation : CGPoint){
        //do some stuff with translation
    }
}

Upvotes: 2

Christopher Kevin Howell
Christopher Kevin Howell

Reputation: 1505

Generally your Objective-C class needs to know about your Swift class that holds the translationMadeDelegate.

On allocation of your Swift class, your Objective-C class can pass itself as the delegate. This is similar to a UIViewController having a UITableView property and setting itself as the delegate / datasource.

Upvotes: 0

Related Questions