协议不返回值

时间:2019-01-11 09:12:13

标签: ios swift protocols

我正在研究协议并得到了一个提示

ViewController1.swift

protocol filterApplied {
    func appliedFiiler(isApplied: Bool)
}

class  : UIViewController{
   var delegate : filterApplied?


   // on some button action
    delegate?.appliedFiiler(isApplied: true)
}



ViewController2.swift

class ViewController2 : UIViewController,filterApplied {
         func appliedFiiler(isApplied: Bool) {
        if isApplied{
            filterButton.imageView?.image = UIImage(named: "filter_applied")
        }
    }
}

现在我知道这不会做任何事情

因为我尚未将委托分配给self。

我该如何在何处执行此操作,以便2 swift文件中的AppliedFilterFunction起作用?

2 个答案:

答案 0 :(得分:0)

您必须将委托连接到ViewController2的自身。

 protocol FilterApplied {

     func appliedFiiler(isApplied: Bool)

 }

 Class ViewController1: UIViewController {

     var delegate: FilterApplied?


 @IBaction func onClick() {

    self.delegate?.appliedFiiler(isApplied: true)

  }

在Viewcontroller2中,您必须将委托连接到self。通过导航控制器或演示控制器。在这种情况下,我已连接到演示控制器。

 Class ViewController2: UIViewController, FilterApplied {


    func onPresent() {

        let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
        vc.delegate = self
        self.present(vc, animated: false, completion: nil)

   }


   func appliedFilter(isApplied: Bool) {

        if isApplied{

           filterButton.imageView?.image = UIImage(named: "filter_applied")

        }

   }


}

答案 1 :(得分:0)

您可能想要这样的东西

//ViewController1.swift
// definition
protocol FilterApplied: class {
    var filterButton: UIButton! { get set }
    func appliedFilter(isApplied: Bool)
}
// defaults protocol behaviour
extension FilterApplied {
    //
    func appliedFilter(isApplied: Bool) {
        if isApplied{
            filterButton.imageView?.image = UIImage(named: "filter_applied")
        }
    }
}


//ViewController2.swift

class ViewController2: UIViewController, FilterApplied {

    @IBOutlet var filterButton: UIButton! {
        didSet {
            // used defaults
            appliedFilter(isApplied: true)
        }
    }
    // overrides defaults
    func appliedFilter(isApplied: Bool) {

    }
} 

最后,您可以选择使用默认行为或添加新行为。