繁体   English   中英

iOS(Swift):用于UIViewController的协议,用于添加新对象

[英]iOS (Swift): Protocol for UIViewController that adds a new object

我有一个视图控制器,负责添加新对象,例如新联系人。 此视图控制器( AddContactViewController )在UINavigationBar上具有以下UIBarButtonItem ,该UIBarButtonItem已禁用,直到提供足够的信息以启用它为止。 然后,当按下此按钮时,将调用一个方法( doneButtonPressed )。

布局如下:

class AddContactViewController: UIViewController {

    @IBOutlet weak var doneButton: UIBarButtonItem! {
        didSet {
            doneButton.isEnabled = false
            doneButton.target = self
            doneButton.action = #selector(self.doneButtonPressed)
        }
    }

     @objc fileprivate func doneButtonPressed() {
         // do some stuff ...
         self.dismiss(animated: false, completion: nil)
     }

}

因为这是很常见的事情,并且有很多样板代码,所以我一直在研究协议AddingHandler但还没有弄清楚如何将UIBarButtonItem作为weak变量连接到storboard或这甚至是正确的方法。

protocol AddingHandler {
    var doneButton: UIBarButtonItem? { get set }
    func doneButtonPressed()
}

extension protocol where Self: UIViewController {
    func configureDoneButton() {
        doneButton.isEnabled = false
        doneButton.target = self
        doneButton.action = #selector(self.doneButtonPressed)        
    }
}

任何帮助或意见,使这项工作将不胜感激。

问题:如何最好地将weak UIButton添加到协议中,然后可以将其挂接到UIViewController实现它的故事板上? 由于这里有很多重复的代码,我是否希望拥有另一个AddSomethingViewController我想知道是否有一种更整洁的方法,只需编写一次(在带有扩展名的协议中),然后在添加了某些内容的任何视图控制器中调用该协议新...

您只需在viewDidLoad()配置doneButton

override func viewDidLoad()
{
    super.viewDidLoad()
    doneButton.isEnabled = false
    doneButton.target = self
    doneButton.action = #selector(self.doneButtonPressed)
}

编辑1:

@objc protocol AddingHandler
{
    var doneButton: UIBarButtonItem? { get }
    @objc func doneButtonPressed()
}

extension AddingHandler where Self: UIViewController
{
    func configureDoneButton()
    {
        doneButton?.isEnabled = false
        doneButton?.target = self
        doneButton?.action = #selector(doneButtonPressed)
    }
}

class AddContactViewController: UIViewController, AddingHandler
{
    @IBOutlet weak var doneButton: UIBarButtonItem!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        configureDoneButton()
    }

    func doneButtonPressed()
    {
        // do some stuff ...
        self.dismiss(animated: false, completion: nil)
    }
}

我已经使用ObjC运行时来解决此问题。 尝试在最终实现它,并检查它是否适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM