[Swift实际操作]八、实用进阶,7使用通知的方法进行对象间的消息传递

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

本文将为你演示,如何使用Notification Center进行消息的传递。

通知中心是一个调度消息通知的类,采用单例设计模式,实现数据传递,回调等功能。

首先打开自定义视图的代码文件(CustomView.swift)

 1 import UIKit
 2 //使当前的自定义类,遵循文本输入框代理协议
 3 class CustomView: UIView,UITextFieldDelegate{
 4 //给自定义类添加一个文本框类型的属性
 5     var textField: UITextField!
 6 
 7 //重写初始化方法,
 8     override init(frame: CGRect)
 9     {
10        super.init(frame: frame)
11 //接着对文本框属性进行初始化,并设置它的显示区域
12        textField = UITextField(frame:CGRect(x: 0,
13                                             y: 0,
14                                         width: self.frame.size.width,
15                                        height: self.frame.size.height))
16 //设置文本框字体大小
17         textField.font = UIFont.boldSystemFont(ofSize: 14)
18 //设置文本框字体颜色
19         textField.textColor = .purple
20 //设置文本框投影颜色
21         textField.layershadowColor = UIColor.black.cgColor
22 //设置文本框投影偏移距离
23         textField.layershadowOffset = CGSize(width: 0.0,height: 3.0)
24 //设置文本框的不透明度
25         textField.shadowOpacity = 0.45
26 //设置阴影的半径大小
27          textField.shadowRadius = 3
28 //设置文本框大背景颜色
29          textField.backgroundColor = .lightGray
30 //设置文本框的代理对象
31          textField.delegate = self
32 
33 //将文本框添加到自定义视图之中
34          self.addSubview(textField)
35       }
36 
37 //实现文本框代理协议中的方法,用来监听键盘上的回车键被按下的事件
38      func textFieldShouldReturn(_ textField: UITextField) -> Bool
39      { 
40 //获得通知中心的单例对象,发送一条指定名称的通知,
41 //并设置通知中心传递的数据为空。
42          NotificationCenter.default.post(name: NSNotification.Name(rawValue:"checkFormNotification"),
43                                  object: nil, 
44                                      userInfo: nil)
45          return true    
46        }
47 
48 //需要实现指定的初始化方法
49     required init?(coder aDecoder: NSCoder)
50     {
51         fataError("init(coder:) has not been implemented")
52      }
53 
54      override func didReciveMemoryWarning(){
55           super.didReceiveMemoryWarning()
56 
57      }
58 }

然后在左侧的项目导航区,打开视图控制器的代码文件(ViewController.swift)

 1 import UIKit
 2 
 3 class ViewController: UIViewController{
 4 //添加两个自定义视图类型的属性
 5      var nameField: CustomView! 
 6      var passwordField: CustomView! 
 7 //添加一个提交按钮,当点击该按钮时,提交整个表单。
 8      var submitButton: UIButton!    
 9 
10      override func viewDidLoad(){
11          super.viewDidLoad()
12 
13 //初始化两个整形常量,作为自定义视图的宽度和高度
14          let wid = Int(self.view.frame.size.width) - 40
15          let hei = 40
16 
17 //然后对第一个自定义视图属性进行初始化,并设置它的显示区域
18          nameField = CustomView(frame: CGRect(x: 20,y: 80,with: wid,height: hei))
19 
20 //对第二个自定义视图属性进行初始化,并设置它的显示区域
21          passwordField= CustomView(frame: CGRect(x: 20,y: 140,with: wid,height: hei))
22 
23 //初始化提交按钮属性,并设置它的显示区域
24          submitButton = UIButton(frame: CGRect(x: 20,y: 240,with: wid,height: hei))
25 //设置按钮在正常状态下的标题文字
26          submitButton.setTitle("Sumbit",for: .normal)
27 //给按钮对象绑定点击事件
28          submitButton.addTarget(self, 
29                               action: #selector(ViewController.submitForm(_:)),
30                                  for: .touchUpInside)
31 //设置按钮对象的背景颜色为灰色
32          submitButton.backgroundColor = .gray
33 //并设置按钮对象为不会响应交互事件的状态
34 //只有当文本框中的内容都被检验成功时,该按钮的状态才会恢复为正常。
35          submitButton.isEnabled = false
36 //将按钮对象添加到当前视图控制器的根视图
37          slef.view.addSubview(submitButton)    
38 
39 //获得通知中心的单例对象,并通过addObserver,对指定名称的通知进行监听,
40 //当收到指定名称的通知时,调用选择器中的checkForm方法。
41           NotificationCenter.default.addObserver(self, 
42                  action: #selector(ViewController.checkForm(_:)),
43                    name: NSNotification.Name(rawValue:"ceckFormNotification"),
44                  object: nil)    
45      }
46    
47 //当点击按钮时在控制台输出一条日志语句,模拟表单的动作
48      @objc func submitForm(_ sender: UIButton)
49      {
50           print("summitForm...")
51       }
52 
53 //接着添加一个方法,用来响应自定义视图中的文本框的回车键被按下的事件
54      func checkForm(_ notification: Notification?)
55      {
56 //当键盘中的回车键被按下时,对两个自定义视图中的文本框进行检验
57           if self.nameField.textField.text != "" && self.passwordField.textField.text != ""
58           {
59 //当两个文本框中的内容都不为空时,恢复提交按钮的可交互性,
60 //并调整按钮的背景颜色为橙色
61                self.submitButton.isEnabled = true
62                submitButton.backgroundColor = .orange      
63            } 
64            else
65           {
66 //当两个文本框中的内容有一个不为空,或者全部为空时,设置按钮不可进行点击
67 //背景颜色改为灰色。
68                self.submitButton.isEnabled = false
69                self.submitButton.backgroundColor = .gray 
70             }     
71       }  
72 
73 //在该类文件中,添加一个析构方法,当该类的实例对象被销毁时,
74 //及时移除通知中心,以免造成资源的浪费
75      deinit
76      {
77          NotificationCenter.default.removeObserver(self)
78       } 
79  
80      override func didReciveMemoryWarning(){
81           super.didReceiveMemoryWarning()
82 
83      }
84 }

此时自定义视图广播了一条指定名称的通知,并由控制器捕捉到了同名的通知。

由于两个文本框中的内容不为空,所以按钮对象的背景颜色变成了橙色。