ios - 如何将自己设置为委托(delegate)?

标签 ios swift delegates

当用户按下 ViewController1 中的按钮时,我希望它调用 ViewController2 中的函数。我认为我唯一缺少的就是将 ViewController2 指定为其自己的委托(delegate),但是如何将 self 声明为委托(delegate)?

ViewController1

protocol VC1Delegate {
    func pushThisButton(_ sender: UIButton)
}

class ViewController1: UIViewController {

    var delegate: VC1Delegate!
    var theButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        buildButton()

    }

    func pushButton(_ sender: UIButton) {
        delegate.pushThisButton(theButton)
    }

    func buildButton() {
        theButton = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
        theButton.backgroundColor = UIColor.black
        theButton.addTarget(self, action: #selector(pushButton), for: .touchUpInside)
        self.view.addSubview(theButton)
    }

}



View Controller 2

class ViewController2: UIViewController, VC1Delegate {

    // I'm guessing somewhere here I need to declare myself as the delegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func pushThisButton(_ sender: UIButton) {
        print("Damnit, Jack! Push the damn button!")
    }

}

最佳答案

当你实例化VC2时,你应该给它分配委托(delegate)。 例如:

 protocol VC1Delegate: class {
     func pushThisButton(_ sender: UIButton)
 }

 class ViewController1: UIViewController {

     weak var delegate: VC1Delegate?

...

let vc2 = ViewController2() 
self.delegate = vc2 // we are in the VC1 context 
self.navigationController.pushViewController(vc2, animated: true)

关于ios - 如何将自己设置为委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45807218/

相关文章:

ios - 如何为 UIView 制作基于图像的平铺背景,使其无法缩放?

arrays - 创建并迭代字典数组的数组

c# - 起订量。模拟委托(delegate)输入

iphone - 具有委托(delegate)方法的 NSTimer

ios - SKSpriteNode 从屏幕上消失后如何删除或销毁它

ios - 如何使用 Swift 使 UILabel 的边缘变圆

iphone - 将 UITableView 信息存储在单个 NSMutableArray 中

ios - 如果使用 ScrollView ,内容 View 宽度不占用主视图宽度

swift - Post 在 Kitura 中将 Request Body 设为 nil

c# - 从使用委托(delegate)搜索不同属性的对象中返回属性?