当前位置:网站首页>Utilisation de la fermeture / bloc de base SWIFT (source)
Utilisation de la fermeture / bloc de base SWIFT (source)
2022-06-24 08:11:00 【Feng hanxu】
J'ai toujours pensé que je n'écrivais pas sur la technologie,C'est un sentiment.,Les tutoriels individuels sont des traces de leur propre chemin.Le succès professionnel est le plus reproductible,J'espère que mon chemin vous permettra d'éviter les détours,J'espère pouvoir vous aider à effacer la poussière de la connaissance,J'espère pouvoir vous aider à comprendre le contexte de la connaissance,J'espère que vous et moi serons au Sommet de la technologie du futur.
(Swift)Fermeture en tant qu'attribut–Adresse de téléchargement du code source
(Swift)Fermeture comme paramètre de méthode–Adresse de téléchargement du code source
(Swift)Constructeur de fermeture–Adresse de téléchargement du code source
Préface
Cette année2022L'année a été réutiliséeswiftLangues,4Utilisé il y a des années,Ça fait longtemps que ça n'a pas marché,Il faudra du temps pour s'y habituer.Après toutswiftTaux d'utilisationocBeaucoup plus flexible.,Voici un enregistrement de mon utilisation habituelle des fermetures
Moi aussi.ocUtilisation de la langueblockArticle de
OC Écouter-Block/Agents/Notification/KVO(Code source)
Etblock Problèmes liés à l'utilisation des applications cycliques
OC Technique BlockProblème de référence circulaire(Vidéo)(Code)
C'est vrai.
Les fermetures sont le plus souvent utilisées pour inverser les données
Utilisation des fermetures comme attributs
Ça vaut le coupVC
1. Créer une fermeture 
Appeler une fermeture dans une méthode de valeur , Passer la valeur à la fermeture 
Cliquez sur le bouton pour démarrer , Tout comme le réseau demande des données 
import UIKit
class BViewController: UIViewController {
let btn = UIButton()
// Redéfinir le type de fermeture
typealias StudentCallBlock = (_ name:String, _ age:String, _ gengder:String) -> ()
// Créer des propriétés de fermeture
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)
}
// Il y a une méthode de données
private func getDate(){
let name = "juan"
let age = "12"
let gender = "gril"
// Transférer les données dans une fermeture et les enregistrer
studentCallBlock!(name,age,gender)// Si la fermeture n'est pas mise en œuvre à l'extérieur, elle s'effondrera.
}
@objc private func btnClick() {
// Acquisition analogique de données réseau
getDate()
navigationController?.popViewController(animated: true)
}
}
Le Contrôleur qui veut la valeur
La valeur transmise peut être obtenue en cliquant sur l'attribut de sortie de l'objet 
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)
}
}
Fermeture comme paramètre de méthode
Contrôleur avec valeur
Définir le type de fermeture 
Créer une méthode avec des paramètres de fermeture , Utiliser des fermetures pour passer des valeurs 
import UIKit
class BViewController: UIViewController {
// Redéfinir le type de fermeture
typealias StudentCallBlock = (_ name:String, _ age:String, _ gengder:String) -> ()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
//Prends ça.Block Mettez - le dans la méthode. , Utilisé pour les appels externes pour obtenir des valeurs
func userBlock(callBlock: @escaping StudentCallBlock){
callBlock("name","age","gender")
}
}
Le Contrôleur qui veut la valeur
Cliquez sur le bouton pour appeler la méthode de fermeture de l'objet , Pour obtenir la valeur passée 
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),")
}
}
}
Fermeture écrite dans le constructeur
Parfois, je vois quelqu'un d'autre écrire. , Les fermetures sont écrites dans le constructeur , En général, une surface de commande doit être éjectée viewBoîte de sélection pour, Ensuite, choisissez - le et donnez - lui l'information que vous voulez. .
Contrôleur avec valeur
Définir la forme de fermeture 
Dans le constructeur , Associer les fermetures 
Passez la valeur à la fermeture de départ 
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()
}
}
Le Contrôleur qui veut la valeur
La fermeture imprime la valeur désirée dans les paramètres du constructeur 
Cliquez sur le bouton pour passer la fermeture 
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()
}
}
边栏推荐
- 有关iframe锚点,锚点出现上下偏移,锚点出现页面显示问题.iframe的srcdoc问题
- The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain
- Part 1: building OpenGL environment
- Ad-gcl:advantageous graph augmentation to improve graph contractual learning
- OC Extension 检测手机是否安装某个App(源码)
- 直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
- Solve the problem of notebook keyboard disabling failure
- On the H5 page, the Apple phone blocks the content when using fixed to locate the bottom of the tabbar
- Resolution error: LNK2019 unresolved external symbol
- Unity culling related technologies
猜你喜欢

单片机STM32F103RB,BLDC直流电机控制器设计,原理图、源码和电路方案

1279_VMWare Player安装VMWare Tools时VSock安装失败解决

第 2 篇:繪制一個窗口

热赛道上的冷思考:乘数效应才是东数西算的根本要求

FPGA的虚拟时钟如何使用?

Keep one decimal place and two decimal places

Model effect optimization, try a variety of cross validation methods (system operation)

Installation and use of selenium IDE

Resolution error: LNK2019 unresolved external symbol

Application of JDBC in performance test
随机推荐
The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain
Shader common functions
Leetcode 207: course schedule (topological sorting determines whether the loop is formed)
Pair class notes
Online education fades
Atguigu---15- built in instruction
没有专业背景,还有机会成为机器学习工程师吗?
有关iframe锚点,锚点出现上下偏移,锚点出现页面显示问题.iframe的srcdoc问题
2022 PMP project management examination agile knowledge points (1)
Optimization and practice of Tencent cloud EMR for cloud native containerization based on yarn
Methods of vector operation and coordinate transformation
"Adobe international certification" about Adobe Photoshop, creating and modifying brush tutorials?
How to cancel the display of the return button at the uniapp uni app H5 end the autobackbutton does not take effect
Getting started with crawler to giving up 06: crawler play Fund (with code)
Unity culling related technologies
不止于观测|阿里云可观测套件正式发布
Smart pointer remarks
Using kubeconfig files to organize cluster access
From jsonpath and XPath to spl
Chapitre 2: dessiner une fenêtre