如何在Swift中正确实现UIViewController和UIView之间的协议委托模式

时间:2014-11-25 02:58:32

标签: ios xcode swift uiviewcontroller

我无法将子类UIView中的协议委托模式实现为UIViewController

目前,这就是我所拥有的:

ViewController.swift

class ViewController: UIViewController,OVAddPersonDialogViewDelegate {

//MARK: IBActions

@IBAction func barBtnActionAdd(sender: UIBarButtonItem) {
    addPersonDialogView!.showInView(self.view)
}

//MARK: Variables

var addPersonDialogView: OVAddPersonDialogView?


//MARK: View LifeCycle

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.addPersonDialogView = OVAddPersonDialogView(frame: self.view.bounds)
    self.addPersonDialogView!.addressList = ["Address1", "Address2", "Address3"]
    addPersonDialogView!.setDelegate(self)

}

//MARK: OVAddPersonDialogViewDelegate

func onClose() {
    println("Close")
}

func onOpen(){
    println("Open")
}

...
...    

}

OVAddPersonDialogView.swift

protocol OVAddPersonDialogViewDelegate: NSObjectProtocol{
   func onClose()
   func onOpen()
}

class OVAddPersonDialogView: UIView, UITableViewDataSource, UITableViewDelegate {

    var delegate: OVAddPersonDialogViewDelegate?

    //MARK: IBActions

    @IBAction func btnCancelAction(sender: UIButton) {
        dismissFromView()
    }

//MARK: Constructor

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

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

//MARK: Instance Methods

func setDelegate(tdelegate:OVAddPersonDialogViewDelegate){
    self.delegate = tdelegate
    println(self.delegate!)
}

private func setupView(){

  let ovAddPersonDialogView:UIView = NSBundle.mainBundle().loadNibNamed("OVAddPersonDialogView", owner: self, options: nil).first as UIView
    ovAddPersonDialogView.frame = CGRectMake(0,0,UIScreen.mainScreen().applicationFrame.size.width, UIScreen.mainScreen().applicationFrame.size.height)
    self.addSubview(ovAddPersonDialogView)

}

func showInView(view:UIView){
    view.addSubview(self)
    self.delegate?.onOpen()
    println(self)
}

func dismissFromView(){
    println("Should close")
    println(self.delegate)
    println(self)
    self.delegate?.onClose()
}

   ...
   ...

}

我想要做的是每当用户点击取消按钮(我知道调用ViewController中的btnCancelAction()方法)时更新OVAddPersonDialogView class

现在,问题是self.delegate?.onClose()类中的ViewController方法实现永远不会被调用。执行showInView(uiView)方法的行为符合预期,但由于某种原因,调用dismissFromView() self.delegate时会变为零。

selfshowInView()方法中记录dismissFromView()后,我注意到self不同。因此,回答了为什么代表成为 nil 的问题。

现在,我想知道在调用selfshowInView()方法之后,dismissFromView()是如何出现在不同实例中的?

对我的问题的任何想法将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

所以我想出了自己问题的答案。真正的问题存在于OVAddPersonDialogView nib 文件中。我没有将其文件所有者的自定义类设置为OVAddPersonDialogView,而是将其置于根View的自定义类中,从而导致init(coder aDecoder: NSCoder)被调用,创建self

的单独实例