当前位置:网站首页>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()
}
}
边栏推荐
- Latest news of awtk: new usage of grid control
- Decltype usage introduction
- Ad-gcl:advantageous graph augmentation to improve graph contractual learning
- Duilib display memory picture
- Moonwell Artemis is now online moonbeam network
- 工控机防破解
- Chapter 3 curve graph of canvas
- 研究生英语期末考试复习
- Practice of opengauss database on CentOS, configuration
- Timer usage notes
猜你喜欢

毕业两年月薪36k,说难也不难吧

1-4metasploitable2介绍

第 1 篇:搭建OpenGL环境

Vulnhub靶机:BOREDHACKERBLOG_ CLOUD AV

The monthly salary of two years after graduation is 36K. It's not difficult to say

The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain

C语言_字符串与指针的爱恨情仇

Latest news of awtk: new usage of grid control

Screenshot recommendation - snipaste

From jsonpath and XPath to spl
随机推荐
JDBC 在性能测试中的应用
The monthly salary of two years after graduation is 36K. It's not difficult to say
一文理解同步FIFO
decltype用法介绍
Four models of iPhone 13 series have been exposed, and indeed, they are 13 fragrant!
June 27, 2021: given a positive array arr, it represents the weight of several people
Synchronous FIFO
Duilib display memory picture
auto使用示例
Graphmae ---- quick reading of papers
Opening chapter of online document technology - rich text editor
Upgrade Mysql to the latest version (mysql8.0.25)
单片机STM32F103RB,BLDC直流电机控制器设计,原理图、源码和电路方案
Leetcode 207: course schedule (topological sorting determines whether the loop is formed)
Chapter 1 overview of canvas
Screenshot recommendation - snipaste
[test development] first knowledge of software testing
Resolution error: LNK2019 unresolved external symbol
Tuple remarks
某问答社区App x-zse-96签名分析