zoukankan      html  css  js  c++  java
  • 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的设置:

  • 相关阅读:
    POI_Excel表格数据导入导出实例--支持xls/xlsx格式
    js图片压缩工具---base64码上传插件,兼容h5和微信端(lrz.mobile.min.js)
    同一个页面,加载不同版本jQuery
    This method isn't transactional
    jquery.cookie的使用,记住用户名
    正则表达式 2017/6/12
    kSet 2017/6/6
    差分与二维差分
    求组合数
    高精度
  • 原文地址:https://www.cnblogs.com/hero11223/p/9347468.html
Copyright © 2011-2022 走看看