Mike Mike - 6 months ago 8x
Swift Question

Swift Delegate function not being executed

I have a UIPageViewcontroller containing three ViewControllers. One Viewcontroller is my ProfileViewcontroller. I have a button in my ProfileViewController, which should tell the UIPageViewCongtroller when pressed, to switch to the next Viewcontroller.
It's my first time implementing a delegate, but I just can't figure out why its not working.

UIPageViewController class:

class PageViewController: UIPageViewController, ProfileViewControllerDelegate {

private(set) lazy var orderedViewControllers: [UIViewController] = {

// The view controllers will be shown in this order
return [self.newColoredViewController("Search"),

override func viewDidLoad() {

dataSource = self

if orderedViewControllers.count >= 2 {


// MARK: ProfileViewControllerDelegate
func profileViewControllerDidTouchOffer(viewController:ProfileViewController, sender: AnyObject) {
print("I'm pressing the offer Button")

ProfileViewController class:

protocol ProfileViewControllerDelegate : class {
func profileViewControllerDidTouchOffer(controller: ProfileViewController, sender: AnyObject)

class ProfileViewController: UIViewController {

weak var delegate: ProfileViewControllerDelegate?

@IBOutlet var profileImageView: SpringImageView!
@IBOutlet var offerButton: UIButton!

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
@IBAction func offerButtonTouchUpInside(sender: AnyObject) {

delegate?.profileViewControllerDidTouchOffer(self, sender: sender)



Looks like you're using the InterfaceBuilder so I'm not sure how it's done there (probably in prepareForSegue), but a typical pattern is something like this:

let vc = ProfileViewController() 
vc.delegate = self // Or whatever you want to act as the delegate 
// Now show the view controller. 

The key is that before using the view controller, you make sure it's delegate property is set to the thing that is the delegate and conforms to the protocol. Typically the calling controller would be the delegate.

EDIT: If you're using the UIPageViewController, then you should add the delegate to the viewController before passing it to setViewControllers https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIPageViewControllerClassReferenceClassRef/#//apple_ref/occ/instm/UIPageViewController/setViewControllers:direction:animated:completion: