delegate:委托,代理 类中有属性,方法,事件 delegate与事件有关 protocol:协议,与类相似,但是其中属性,方法,事件没有具体内容 当class遵守协议之后,需要实现这个协议中的某一些函数。
delegate的使用 例如在获取地址的方法里
import CoreLocation class ViewController: UIViewController,CLLocationMangerDelegate { //加入delegate let locationManager = CLLocationManager() //引入需要使用的方法,locationManager为CLLocationManager()的实例 override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let lat = locations[0].coordinate.latitude let lon = locations[0].coordinate.longitude }目标:获取经度和纬度 1.使用Xcode自带的功能包CoreLocation
2.将其实例化之后进行用户授权,在info中加入描述
3.在系统提供的功能包中,如现在的CoreLocation中,要使用其中的CLLocationManager方法,需要让ViewLController遵守CLLocationManagerDelegate协议,也是要让ViewController实现这个函数。 所以在调用locationManager获取地址时候,需要让ViewController知道这个协议的代理人是VC自己,故而需要在ViewDidLoad中写入locationManager.delegate = self,从而形成一个闭环
locationManager的代理人是ViewController,亦可以说是ViewController实现了locationManager
两个页面间的传值
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "selectCity"{ let vc = segue.destination as! SelectCityController //as!向下转型 //if let vc = segue.destination as? SelectCityController vc.currentCity = weather.city//正向传值 } }用segue.destination可以得到要跳转到的Controller,segue是链接两个页面的箭头,segue.identifier用来判断要跳转去哪个页面 随着箭头指向的方向,进行正向传值。
反向传值:
//1,自定义了一个协议及里面的事件方法 protocol SelectCityDelegate { func didChangeCity(city:String) } //2,规定谁可以触发这些事件方法 var delegate:SelectCityDelegate? //3,在哪里触发这些事件函数呢 @IBAction func changeCity(_ sender: Any) { //问号的意思:delegate有值则继续执行后面的调用,若为nil,则不执行后面的调用 delegate?.didChangeCity(city: cityInput.text!) //销毁当前页面 dismiss(animated: true, completion: nil) }