Arti February 2016

Protocol not wroking from container

I have a ViewController with two overlapping ContainerViews. And from one of child views i would want to change tab to another.

enter image description here

I created a protocol:

protocol pickerDelegate {
    func changeMainContainer(index:Int)
}

In child view:

class ChildViewInContainerController: UIViewController, UIPickerViewDelegate {
    var delegateStorePicker:storePickerDelegate?
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.delegatePicker?.changeMainContainer(0)
    }
}

In Main view:

class MainViewController: UIViewController, storePickerDelegate {
    func changeMainContainer(index:Int) {
        switch index {
            case 0 :
                self.container1.hidden = true
                self.container2.hidden = false
            case 1:
                self.container1.hidden = false
                self.container2.hidden = true
            default: break;
        }
    }
}

Code works, but changeMainContainer function not been called.

Answers


Eendje February 2016

Protocol: (notice I changed the protocol conforming class)

protocol PickerDelegate: class {
    func changeMainContainer(index:Int)
}

ChildView: (Changed your delegate to a weak var)

class ChildViewInContainerController: UIViewController, UIPickerViewDelegate {
    weak var delegateStorePicker: PickerDelegate?
}

Main view:

class MainViewController: UIViewController, PickerDelegate {

    // I don't know how you create your view
    func createChild() {
        let controller = ChildViewInContainerController()
        controller.delegateStorePicker = self

        // Your own implementation
    }
}

Making the delegate weak prevents a strong reference cycle.

Post Status

Asked in February 2016
Viewed 3,021 times
Voted 9
Answered 1 times

Search




Leave an answer