swift基础利用闭包在两个视图界面传值

前端之家收集整理的这篇文章主要介绍了swift基础利用闭包在两个视图界面传值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

视图ViewController


class ViewController: UIViewController{
    
    @IBOutlet weak var valueLabel: UILabel!
    
    
    var secVC:SecondController = SecondController()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        secVC.myClosure = {(text:String) -> Void in
        
            print("\(text)")
            self.valueLabel.text = text
        }
    }
    
    @IBAction func push() {
        
        self.navigationController?.pushViewController(secVC,animated: true)
        
        
    }

}



视图二

import UIKit

// 闭包
typealias sendValueClosure = (text:String)->Void

class SecondController: UIViewController {

    var myClosure:sendValueClosure?
    
    var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.redColor()
        textField = UITextField(frame: CGRectMake(30,100,260,30))
        textField.borderStyle = UITextBorderStyle.RoundedRect
        self.view.addSubview(textField)
        
      let btn = UIButton(frame: CGRectMake(30,150,30))
        btn.setTitle("click",forState: UIControlState.Normal)
        btn.addTarget(self,action: #selector(SecondController.click),forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(btn)
    }

    
    // 点击这里传值过去
    func click() {

        let str:String = textField.text!
        
        if (myClosure != nil){
            myClosure!(text:str)
        }
        
        self.navigationController?.popViewControllerAnimated(true)
           
    }

}


当点击click
运行结果为
原文链接:https://www.f2er.com/swift/323512.html

猜你在找的Swift相关文章