当前位置:网站首页>Use of swift basic closure /block (source code)

Use of swift basic closure /block (source code)

2022-06-24 08:13:00 Fenghanxu

I always feel that what I write is not technology , But feelings , One tutorial after another is the trace of one's own journey . Success with expertise is the most replicable , I hope my path will make you less detours , I hope I can help you erase the dust of knowledge , I hope I can help you clarify the context of knowledge , I hope there will be you and me on the top of technology in the future .

(Swift) Closures as attributes – Source code download address

(Swift) Closures as method parameters – Source code download address

(Swift) Closure constructor – Source code download address

Preface

This year, 2022 Used it again in swift Language ,4 Used it years ago , It's been a long time , It will take time to get used to it . After all swift The use of oc Much more flexible , The following is a record of my usual use of closures

I used to oc Language use block The article
OC monitor -Block/ agent / notice /KVO( Source code )

and block It is easy to cause problems of cyclic application
OC technology Block The problem of circular quotation ( video )( Code )

On the subject

Closures are most commonly used for data retransmission

Use of closures as attributes

Valuable VC

1. Create a closure
 Insert picture description here
Call a closure inside a method that has a value , Pass the value into the closure
 Insert picture description here
Click the button to start , Just like the network requests data
 Insert picture description here

import UIKit

class BViewController: UIViewController {
    
    let btn = UIButton()

    //  Redefine closure types 
    typealias StudentCallBlock = (_ name:String, _ age:String, _ gengder:String) -> ()
    
    //  Create closure properties 
    var studentCallBlock:StudentCallBlock?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        btn.setTitle("pop", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .orange
        btn.frame = CGRect(x: 100, y: 250, width: 50, height: 50)
     
    }
    
    // With data method 
    private func getDate(){
        let name = "juan"
        let age = "12"
        let gender = "gril"
        // Pass the data to the closure and save it 
        studentCallBlock!(name,age,gender)// If the closure is not implemented outside, it will collapse 
    }
    
    @objc private func btnClick() {
        // Simulate the acquisition of network data 
        getDate()
        navigationController?.popViewController(animated: true)
    }

}

The controller that wants to get the value

You can get the passed value by clicking the attribute of the object
 Insert picture description here

import UIKit
import SnapKit

class ViewController: UIViewController {

    let btn_0 = UIButton()
    let btn_1 = UIButton()
    let vc = BViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    
        view.addSubview(btn_0)
        btn_0.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        btn_0.setTitle("dump", for: .normal)
        btn_0.titleLabel?.font = .systemFont(ofSize: 14)
        btn_0.setTitleColor(.white, for: .normal)
        btn_0.backgroundColor = .orange
        btn_0.frame = CGRect(x: 100, y: 250, width: 50, height: 50)
        
        vc.studentCallBlock = { name, age, gengder in
            print("studentCallBlock name: \(name), age: \(age), gengder: \(gengder),")
        }
    }

    @objc private func btnClick() {
        navigationController?.pushViewController(vc, animated: true)
    }
}

Closures as method parameters

Controller with value

Define the type of closure
 Insert picture description here

Create a method with closure parameters , Use closures to pass values out
 Insert picture description here

import UIKit

class BViewController: UIViewController {
    
    //  Redefine closure types 
    typealias StudentCallBlock = (_ name:String, _ age:String, _ gengder:String) -> ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }
    
    // hold Block Put it in the method , Used for external calls to get values 
    func userBlock(callBlock: @escaping StudentCallBlock){
        callBlock("name","age","gender")
    }
}

The controller that wants to get the value

Click the button to call the closure method of the object , You can get the passed value
 Insert picture description here

import UIKit
import SnapKit

class ViewController: UIViewController {

    let btn_1 = UIButton()
    let vc = BViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(btn_1)
        btn_1.addTarget(self, action: #selector(btnClick_1), for: .touchUpInside)
        btn_1.setTitle("value", for: .normal)
        btn_1.titleLabel?.font = .systemFont(ofSize: 14)
        btn_1.setTitleColor(.white, for: .normal)
        btn_1.backgroundColor = .orange
        btn_1.frame = CGRect(x: 100, y: 450, width: 50, height: 50)             
    }

    @objc private func btnClick_1() {
        vc.userBlock { name, age, gengder in
            print("userBlock name: \(name), age: \(age), gengder: \(gengder),")
        }
    }
}

Closures are written in constructors

Sometimes I see some other people's writing , The closure is written in the constructor , Generally, a controller needs to pop up a view Selection box for , Then select the information you want to send out and use it in this way .

Controller with value

Define the closure form
 Insert picture description here
In the constructor , Associate closures
 Insert picture description here
The value is passed from the place where the closure starts
 Insert picture description here

import UIKit

public let kScreenWidth: CGFloat = UIScreen.main.bounds.size.width

public let kScreenHeight: CGFloat = UIScreen.main.bounds.size.height

class FloatView: UIView {

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(with valueBlock:((NSInteger)->())?) {
        
        self.valueBlock = valueBlock
        
        let targetRect = CGRect(
            x: 0,
            y: 0,
            width: kScreenWidth,
            height: kScreenHeight
        )
        
        super.init(frame: targetRect)
        
        buildUI()
    }
    
    func showView(){
        UIView.animate(withDuration: 0.5, animations: {
            self.backgroundColor = .black.withAlphaComponent(0.5)
        })
    }
    
    func dismissView(){
        valueBlock?(1)
        
        self.removeFromSuperview()
        backgroundColor = .clear
    }
    
    private let button = UIButton()
    
    private var valueBlock:((_ index:NSInteger)->())?
    
    private var list = [String]()
    
    private func buildUI(){
        backgroundColor = .clear
        
        addSubview(button)
        button.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
    }
    
    @objc func buttonClick() {
        self.dismissView()
    }
}

The controller that wants to get the value

The closure prints the desired value in the constructor parameters
 Insert picture description here
Click the button to pass the closure
 Insert picture description here

import UIKit
import SnapKit

class ViewController: UIViewController {

    let btn_0 = UIButton()
    
    let container = FloatView { index in
        print("index: \(index)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    
        view.addSubview(btn_0)
        btn_0.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        btn_0.setTitle("dump", for: .normal)
        btn_0.titleLabel?.font = .systemFont(ofSize: 14)
        btn_0.setTitleColor(.white, for: .normal)
        btn_0.backgroundColor = .orange
        btn_0.frame = CGRect(x: 100, y: 250, width: 50, height: 50)
           
        view.addSubview(container)
        container.showView()
    }

    @objc private func btnClick() {
        container.dismissView()
    }
    
}
原网站

版权声明
本文为[Fenghanxu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240434142177.html