星空网 > 软件开发 > 操作系统

Swift 协议和委托(代理)

协议 (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 UIKitprotocol 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.  }}

 






原标题:Swift 协议和委托(代理)

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

fba介绍法:https://www.goluckyvip.com/tag/19666.html
fba金手指:https://www.goluckyvip.com/tag/19667.html
fba进仓:https://www.goluckyvip.com/tag/19668.html
FBA进阶之路:https://www.goluckyvip.com/tag/19669.html
意大利电商:https://www.goluckyvip.com/tag/1967.html
fba精品:https://www.goluckyvip.com/tag/19670.html
旅游景点的打油诗 旅游景点的打油诗怎么写:https://www.vstour.cn/a/366180.html
2024深圳龙岗区文化馆免费音乐培训课程安排+报名方式:https://www.vstour.cn/a/366181.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流