• swift开发之--代理协议的使用


    swift代理的使用,和oc版本有区别,区别还是蛮大的,不过和oc一样都是用于反向传值:

    实现如下:

    1,声明两个类

    2,实现流程,viewcontroller页面点击按钮进入firstVC页面,然后在firstVC页面修改值,返回把值传到viewcontroller页面

    3,具体实现:

    a 在firstVC页面声明代理

    import UIKit
    
    class FirstViewController: UIViewController {
    
        @IBOutlet weak var textField: UITextField!
        
        var delegate:EditViewControllerDelegate?
        
        var oldStr:String?
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
            
            if oldStr != nil {
                textField.text = oldStr
            }
            
        }
        @IBAction func sendAction(_ sender: Any) {
            delegate?.edidStr(controller: self, newInfo: textField.text!)
        }
        
        @IBAction func disMissAction(_ sender: Any) {
            delegate?.editStrDidCancel(controller: self)
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

    b 声明代理方法

    protocol EditViewControllerDelegate {
        func edidStr(controller:FirstViewController,newInfo:String)
        func editStrDidCancel(controller:FirstViewController)
    }

    c 代理方法的使用

    import UIKit
    
    class ViewController: UIViewController,EditViewControllerDelegate {
        
        @IBOutlet weak var label: UILabel!
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        //页面跳转时
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "EditView"{
                let controller = segue.destination as! FirstViewController
                //设置代理
                controller.delegate = self
                //将值传递给新页面
                controller.oldStr = label.text
            }
        }
        
        func edidStr(controller: FirstViewController, newInfo: String) {
            label.text = newInfo;
            controller.presentingViewController?.dismiss(animated: true, completion: nil)
        }
        
        func editStrDidCancel(controller: FirstViewController) {
            controller.presentingViewController?.dismiss(animated: true, completion: nil)
        }

    segue的设置:

  • 相关阅读:
    static
    crontab
    coco2d-x 纹理研究
    2048-AI程序算法分析
    如何利用SVN合并代码
    Cocos2d-x 对于中文的支持-----iconv库
    cocos2d-x 2.2 资源更新AssetsManager例子代码
    防止手机游戏衰老的方法
    游戏开发博客
    网络游戏同步法则
  • 原文地址:https://www.cnblogs.com/hero11223/p/9347468.html
Copyright © 2020-2023  润新知