gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:26:56 24 4
gpt4 key购买 nike

我有一个 View Controller ,负责添加新对象,例如新联系人。此 View Controller (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)
}

}

由于这是很常见的事情,并且有很多样板代码,因此我一直在研究协议(protocol)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添加到一个协议(protocol)中,然后可以将其连接到 Storyboard中,其中UIViewController 实现它了吗?由于这里有很多重复的代码,我是否希望有另一个 AddSomethingViewController 我想知道是否有一种更简洁的方法只写一次(在带有扩展的协议(protocol)中)然后调用协议(protocol)任何添加新内容的 View Controller ...

最佳答案

您可以简单地在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 运行时来解决该问题。尝试在最后实现它并检查它是否适合您。

关于iOS( swift ): Protocol for UIViewController that adds a new object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50643017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com