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

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

我有一个视图控制器负责添加一个新对象,比如一个新联系人。此视图控制器 (AddContactViewController) 在 UINavigationBar 上有以下 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 变量,或者这是否是正确的方法。

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 运行时解决了这个问题。尝试在你的最后实现它并检查它是否适合你。