Geethanjali Reddy
Geethanjali Reddy

Reputation: 223

Call delegate without segues or actually adding the view on storyboard

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.

Upvotes: 0

Views: 45

Answers (1)

Munira Chaiwala
Munira Chaiwala

Reputation: 31

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

Upvotes: 0

Related Questions