在Array中的UIView上调用自定义函数

时间:2015-08-25 21:47:01

标签: arrays swift uiview

我有一个具有不同UIViews的数组,但是这些UIViews有相同的方法做不同的事情,我想调用这些方法。我创建的数组与我尝试调用该方法时相比,它不存在于UIView类中。

import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    var pages:Array<UIView>  = []

    let view1:View1 = View1(frame: CGRectMake(0, 0 ,  100 , 100))
    view1.backgroundColor = UIColor.blueColor()
    pages.append(view1)

    let view2:View2 = View2(frame: CGRectMake(100, 100 ,  100 , 100))
    view2.backgroundColor = UIColor.redColor()
    pages.append(view2)

    let view3:View3 = View3(frame: CGRectMake(200, 200 ,  100 , 100))
    view3.backgroundColor = UIColor.orangeColor()
    pages.append(view3)

    //This work
    for myView in pages {
      self.view.addSubview(myView)
    }

    // I would like to call a generic function into a uiview class into array
    for myView in pages {
      myView.generic()
    }

  }

  class View1: UIView {

    override init(frame: CGRect  ) {
      super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }

    func generic(){
      println("A, B, C")
    }

  }

  class View2: UIView {

    override init(frame: CGRect  ) {
      super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }

    func generic(){
      println("X, Y, Z")
    }

  }

  class View3: UIView {

    override init(frame: CGRect  ) {
      super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
    }

    func generic(){
      println("1, 2, 3")
    }

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

1 个答案:

答案 0 :(得分:0)

我们可以声明一个协议并使这些视图都符合它,而不是将这些视图视为UIView,即它们的公共超类。

protocol GenericProtocol {
    func generic()
}

现在,在类定义中,添加此一致性:

class View1: UIView, GenericProtocol { /* ... */ }
// for each class

现在,让我们的数组保持GenericProtocol个对象:

var pages = [GenericProtocol]()

在我们填写完毕后,我们现在可以forin覆盖它,并在其成员上调用GenericProtocol中声明的任何内容:

for page in pages {
    page.generic()
}