Swift:delegate

本文详细介绍Swift中代理模式的实现步骤,包括定义代理方法、声明代理属性、调用代理方法及如何在视图控制器中遵循和实现代理。通过A界面和B界面的交互实例,展示代理模式在iOS开发中的应用。

1.定义代理方法:

@objc protocol ChangeColorDelegate: class {
    /// 必须实现的方法
    func changeClolor(_ clolor:UIColor) 
    /// 非必须实现方法
    @objc optional func mayChangeClolor() -> UIColor
}

///也可以这样声明:
protocol ChangeColorDelegateSwift: class {
    /// 必须实现的方法
    func changeClolor(_ clolor:UIColor)
    /// 非必须实现方法
     
}

2.申明代理属性(weak):

weak var delegate:ChangeColorDelegate?

3.调用代理方法:

   if ((self.delegate?.changeClolor) != nil) {
                   self.delegate?.changeClolor(.red)
               }

4.在需要调用的地方遵循代理

bVC.delegate = self

5.在需要调用的地方写代理方法

extension ViewController:ChangeColorDelegate{
    func changeClolor(_ clolor: UIColor) {
        self.view.backgroundColor = clolor
    }
    
    
}

具体使用方法:

B 界面:

import UIKit

@objc protocol ChangeColorDelegate: class {
    /// 必须实现的方法
    func changeClolor(_ clolor:UIColor) 
    /// 非必须实现方法
    @objc optional func mayChangeClolor() -> UIColor
}

class BViewController: UIViewController {
    weak var delegate:ChangeColorDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .green
        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //调用代理方法
         if ((self.delegate?.changeClolor) != nil) {
                   self.delegate?.changeClolor(.red)
               }
    }
   

}

A界面:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue
        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         self.view.backgroundColor = .blue
        let bVC = BViewController()
//        bVC.modalPresentationStyle = .fullScreen
        ///遵循代理
        bVC.delegate = self
        self.present(bVC, animated: true, completion: nil)
    }
}
///代理方法
extension ViewController:ChangeColorDelegate{
    func changeClolor(_ clolor: UIColor) {
        self.view.backgroundColor = clolor
    }
    
   
    
    
}

 

Swift 中,`delegate: delegateA & delegateB` 这种形式是协议组合,允许一个委托属性同时遵循多个协议。以下是关于其使用和原理的介绍: ### 使用方法 #### 定义协议 首先需要定义 `delegateA` 和 `delegateB` 两个协议,示例如下: ```swift protocol DelegateA { func methodFromA() } protocol DelegateB { func methodFromB() } ``` #### 声明协议组合的委托属性 在类或结构体中声明一个遵循 `DelegateA` 和 `DelegateB` 协议组合的委托属性,通常使用 `weak` 修饰以避免循环引用: ```swift class SomeClass { weak var delegate: (DelegateA & DelegateB)? func callDelegateMethods() { delegate?.methodFromA() delegate?.methodFromB() } } ``` #### 实现协议 创建一个类或结构体来实现 `DelegateA` 和 `DelegateB` 协议: ```swift class DelegateImplementation: DelegateA, DelegateB { func methodFromA() { print("Method from DelegateA is called.") } func methodFromB() { print("Method from DelegateB is called.") } } ``` #### 设置委托并调用方法 将实现了协议的对象赋值给委托属性,并调用相关方法: ```swift let someObject = SomeClass() let delegateObject = DelegateImplementation() someObject.delegate = delegateObject someObject.callDelegateMethods() ``` ### 原理 - **类型检查**:协议组合 `DelegateA & DelegateB` 实际上是一种类型约束,它要求委托属性的类型必须同时遵循 `DelegateA` 和 `DelegateB` 协议。编译器会在编译时检查委托对象是否满足这个约束,如果不满足则会报错。 - **多态性**:通过协议组合,委托属性可以引用任何实现了这两个协议的对象,实现了多态性。代码可以通过委托属性调用协议中定义的方法,而不需要关心具体的对象类型。 - **弱引用**:使用 `weak` 修饰委托属性可以避免循环引用问题。当委托对象被释放时,委托属性会自动置为 `nil`,从而避免访问已释放对象导致的崩溃。 ### 代码示例总结 ```swift // 定义协议 protocol DelegateA { func methodFromA() } protocol DelegateB { func methodFromB() } // 声明协议组合的委托属性 class SomeClass { weak var delegate: (DelegateA & DelegateB)? func callDelegateMethods() { delegate?.methodFromA() delegate?.methodFromB() } } // 实现协议 class DelegateImplementation: DelegateA, DelegateB { func methodFromA() { print("Method from DelegateA is called.") } func methodFromB() { print("Method from DelegateB is called.") } } // 设置委托并调用方法 let someObject = SomeClass() let delegateObject = DelegateImplementation() someObject.delegate = delegateObject someObject.callDelegateMethods() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值