0

Im new to swift and I'm confused how to pass values from container view to parent view. I tried the delegate method but I don't know how to call the delegate method inside the parent.It doesn't seem to work, the app just terminates.

The following code is how display the container.The CameraView is the container view and DiaryEntryViewController is the parent view controller.

@IBAction func cameraBtn(_ sender: Any) {
    CameraView.isHidden = !CameraView.isHidden
    self.view.sendSubview(toBack: diaryEntryText) 
}

And on click of another button, the container should hide and simultaneously pass the data to parent view.I'm able to hide the view by the following code:

@IBAction func saveCamBtn(_ sender: Any) {
  let parent = self.parent as! DiaryEntryViewController
  parent.CameraView.isHidden  = true
}

Is there a way to get the data to parent view.I actually don't want to use segues as the data inside the view should not be lost if I open the container view again.

1 Answers1

0
Here is an example, the Player class delegates the shooting logic to the weapon:

protocol Targetable {
    var life: Int { get set }
    func takeDamage(damage: Int)
}

protocol Shootable {
    func shoot(target: Targetable)
}

class Pistol: Shootable {
    func shoot(target: Targetable) {
        target.takeDamage(1)
    }
}

class Shotgun: Shootable {
    func shoot(target: Targetable) {
        target.takeDamage(5)
    }
}

class Enemy: Targetable {
    var life: Int = 10

    func takeDamage(damage: Int) {
        life -= damage
        println("enemy lost \(damage) hit points")

        if life <= 0 {
            println("enemy is dead now")
        }
    }
}

class Player {
    var weapon: Shootable!

    init(weapon: Shootable) {
        self.weapon = weapon
    }

    func shoot(target: Targetable) {
        weapon.shoot(target)
    }
}

var terminator = Player(weapon: Pistol())

var enemy = Enemy()

terminator.shoot(enemy)
//> enemy lost 1 hit points
terminator.shoot(enemy)
//> enemy lost 1 hit points
terminator.shoot(enemy)
//> enemy lost 1 hit points
terminator.shoot(enemy)
//> enemy lost 1 hit points
terminator.shoot(enemy)
//> enemy lost 1 hit points

// changing weapon because the pistol is inefficient
terminator.weapon = Shotgun()

terminator.shoot(enemy)
//> enemy lost 5 hit points
//> enemy is dead now

Furthermore you can refer this link : https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

  • 1
    Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Mar 20 '18 at 18:23