在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
协议 (Protocols) 语法protocol SomeProtocol {
// protocol definition goes here
}
// 中间以冒号分隔实现协议,有多个协议的话,协议之间逗号分隔
struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
}
// 含有父类的同时实现协议,父类写在协议之前
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
委托(代理)模式 委托是一种设计模式,它允许类或结构体将一些需要它们负责的功能 委托模式的实现很简单: 定义 委托模式可以用来响应特定的动作或接收外部数据源提供的数据,而无需要知道外部数据源的类型 语法FirstViewController的代码
class FirstViewController: UIViewController, SecondViewControllerDelegate { @IBOutlet weak var showDelegateTextLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //点击按钮跳转到SecondViewController @IBAction func tapGoSecondViewController(sender: UIButton) { //从storyboard上加载SecondViewController let secondVC = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController secondVC.delegate = self //跳转到SecondViewController self.navigationController?.pushViewController(secondVC, animated: true) } //MARK: - SecondViewControllerDelegate func fetchBackString(str: String) { self.showDelegateTextLabel.text = str } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
SecondViewController的代码
import UIKit protocol SecondViewControllerDelegate: NSObjectProtocol{ func fetchBackString(str: String) } class SecondViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! weak var delegate: SecondViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func delegateBackMethod(sender: UIButton) { if self.delegate != nil { if let tempString = self.inputTextField.text { delegate!.fetchBackString("代理返回数据:\(tempString)") } } self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
|
请发表评论