1

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");
}
2
  • In your code, delegate will be nil and the app will crash. Commented Apr 11, 2016 at 12:42
  • Usually the delegate is set in or after the init method of the class. Commented Apr 11, 2016 at 12:48

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi. Thank you for your reply. But I want the delegate and the delegate call to be inversed. So the protocol will be in Viewcontroller instead of someClass.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.