当前位置:网站首页>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()
}
}
边栏推荐
- Unity culling related technologies
- Chrono usage notes
- Any remarks
- 解决错误: LNK2019 无法解析的外部符号
- Gossip: what happened to 3aC?
- GraphMAE----論文快速閱讀
- Random number remarks
- 1279_VMWare Player安装VMWare Tools时VSock安装失败解决
- The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain
- Introduction to software engineering - Chapter 2 - feasibility study
猜你喜欢

Backup and restore SQL Server Databases locally

Swift 基础 闭包/Block的使用(源码)

JDBC 在性能测试中的应用

Introduction to software engineering - Chapter 2 - feasibility study

Vulnhub target: boredhackerblog: social network

Examples of corpus data processing cases (reading multiple text files, reading multiple files specified under a folder, decoding errors, reading multiple subfolder text, batch renaming of multiple fil
![[008] filter the table data row by row, jump out of the for cycle and skip this cycle VBA](/img/a0/f03b8d9c8f5e53078c38cce11f8ad3.png)
[008] filter the table data row by row, jump out of the for cycle and skip this cycle VBA

Part 2: drawing a window

From jsonpath and XPath to spl

单片机STM32F103RB,BLDC直流电机控制器设计,原理图、源码和电路方案
随机推荐
GraphMAE----論文快速閱讀
Swift 基础 闭包/Block的使用(源码)
Echart 心得 (一): 有关Y轴yAxis属性
Solution of electric education system for intelligent supervision station
[test development] first knowledge of software testing
JDBC 在性能测试中的应用
4-操作列表(循环结构)
From jsonpath and XPath to spl
Chapter 4 line operation of canvas
1-4metasploitable2介绍
Simple refraction effect
第 2 篇:绘制一个窗口
OC Extension 检测手机是否安装某个App(源码)
直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
3-列表简介
Chapter 2 line graph of canvas
Teach you how to use the reflect package to parse the structure of go - step 1: parameter type check
L1-019 who goes first (15 points)
Solve the problem of notebook keyboard disabling failure
The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain