当前位置:网站首页>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 
Call a closure inside a method that has a value , Pass the value into the closure 
Click the button to start , Just like the network requests data 
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 
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 
Create a method with closure parameters , Use closures to pass values out 
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 
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 
In the constructor , Associate closures 
The value is passed from the place where the closure starts 
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 
Click the button to pass the closure 
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()
}
}
边栏推荐
- [test development] first knowledge of software testing
- [teacher zhaoyuqiang] use the Oracle tracking file
- 【资料上新】迅为基于3568开发板的NPU开发资料全面升级
- Selenium IDE的安装以及使用
- Practice of opengauss database on CentOS, configuration
- Redolog and binlog
- 软件工程导论——第三章——需求分析
- Part 1: building OpenGL environment
- transformers PreTrainedTokenizer类
- Upgrade Mysql to the latest version (mysql8.0.25)
猜你喜欢

Pagoda panel installation php7.2 installation phalcon3.3.2

Screenshot recommendation - snipaste

Swift 基础 Swift才有的特性

Chapitre 2: dessiner une fenêtre

Echart 心得 (一): 有关Y轴yAxis属性

Shader common functions

Introduction to software engineering - Chapter 2 - feasibility study

宝塔面板安装php7.2安装phalcon3.3.2

Swift Extension NetworkUtil(網絡監聽)(源碼)

OC Extension 检测手机是否安装某个App(源码)
随机推荐
Analysis of abnormal problems in domain name resolution in kubernetes
3-list introduction
Selenium IDE的安装以及使用
Optimization and practice of Tencent cloud EMR for cloud native containerization based on yarn
Pagoda panel installation php7.2 installation phalcon3.3.2
从 jsonpath 和 xpath 到 SPL
Gossip: what happened to 3aC?
Swift 基礎 閉包/Block的使用(源碼)
os.path.join()使用过程中遇到的坑
Echart 心得 (一): 有关Y轴yAxis属性
Echart's experience (I): about y axis yaxis attribute
不止于观测|阿里云可观测套件正式发布
How does dating software cut your leeks
Serialization of unity
decltype用法介绍
Simple summary of lighting usage
Oracle advanced SQL qualified query
直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
自动化测试的未来趋势
redolog和binlog