0

我是 swift 新手,我很困惑如何将值从容器视图传递到父视图。我尝试了委托方法,但我不知道如何在父级内部调用委托方法。它似乎不起作用,应用程序刚刚终止。

以下代码是如何显示容器。CameraView 是容器视图,DiaryEntryViewController 是父视图控制器。

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

单击另一个按钮时,容器应该隐藏并同时将数据传递给父视图。我可以通过以下代码隐藏视图:

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

有没有办法将数据获取到父视图。我实际上不想使用 segues,因为如果我再次打开容器视图,视图内的数据不应该丢失。

4

1 回答 1

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

此外,您可以参考此链接:https ://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

于 2018-03-20T09:50:19.943 回答