本篇主要介绍UIView里的delegate 和 protocol的一个简单的example和如何去使用
首先我们先做一个简单的UIView,在ViewController里有一个去到DetailViewController的button,在DetailView里我们有两个Button,一个是blue,一个是red。我们最终的结果是当我们进到detai以后,点击red,第一个View的背景颜色会变成红色,点击blue,背景颜色会变成蓝色
这是我的第一个ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func detailNavigation(_ sender: Any) {
guard let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else { return }
detailVC.delegateColor = self
present(detailVC, animated: true, completion: nil)
}
}
extension ViewController: ColorChangeProtocol {
func changeColor(color: UIColor) {
view.backgroundColor = color
}
}
开始都是比较基本的设定,在点击detaiNavigation这个button之后,会去到detaiViewController,后面到delegateColor和下面的 ColorChangeProtocol之后会讲到,我们先看DetailViewController里的代码
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
var delegateColor: ColorChangeProtocol?
@IBAction func blueButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegateColor?.changeColor(color: .blue)
}
@IBAction func redButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegateColor?.changeColor(color: .red)
}
}
protocol ColorChangeProtocol {
func changeColor(color: UIColor)
}
这里我们有两个button,还有一个delegateColor的var,这里我们先写一个protocol,里面有一个changeColor的function和一个UIColor的input。并把这个function放到两个button里面,这样当我们在点击这两个按钮的时候,就会执行这个function。
现在我们回到第一个UIViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func detailNavigation(_ sender: Any) {
guard let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else { return }
detailVC.delegateColor = self
present(detailVC, animated: true, completion: nil)
}
}
extension ViewController: ColorChangeProtocol {
func changeColor(color: UIColor) {
view.backgroundColor = color
}
}
我们首先在写一个extension,并带入ColorChangeProtocol,这样UIViewController就会有这个delegate。在这个delegate里,我们有一个view.backgroundColor。因为我们在detailView的button里,有call这个function,还有两个不同的颜色input在两个buton里,所以当我们点击这detailNavigation这个button的时候,我们会去到DetailView,同时detailVC里的delegateColor这个var(同时也是ColorChangeProtocol)会变成我们现在的这个tableView。这样当我们点击detailView里的两个button以后,我们主界面的backgroundColor就会变成我们想要的颜色
总结:delegate and protocol 这种方法是一个1对1的communication。所以我们需要两个按钮来执行两种不同的指令。之后我会介绍notification and observer,这是另一种方法,相比delegate不同的是它是1对多的communication。相比较与notification observer,delegate protocol更清晰和仔细一些,当然选择哪一种方式就看当下的需要是哪一种。比如一些warning,error就比较适合用delegate,因为是一对一,方便去追踪。如果是需要多种指令,并且需要有很多变化的var,那就选择notification observer,虽然不如delegate容易追踪,但是写起来会容易很多