我看不到Xcode / Swift中可重复使用的故事板模式的实用方法。我有许多ViewController,它们的行为和外观几乎相同。因此,viewDidLoad()始终相同:
override func viewDidLoad() {
super.viewDidLoad()
labelKESumme.text = something
}
因为每个ViewController都必须配置有自己的类,而Swift缺乏多继承性,所以我尝试创建这样的扩展名:
extension UIViewController {
func show() {
self.labelKESumme.text = something <== ... has no member
}
}
但是由于“没有成员”错误,因此无法正常工作。同样,也无法在标签和扩展代码之间配置插座。需要一种方法来配置许多具有相同内容的视图控制器而无需代码重复。
答案 0 :(得分:0)
您可以使用如下所示的协议扩展
// protocol
protocol Showable {
var labelKESumme: UILabel?
func show()
}
//protocol extension if you want same functionality everywhere
extension Showable {
func show() {
labelKESumme?.text = something
}
}
// just conform the the protocol
ABCViewController: Showable {
}
// just conform the the protocol
XYZViewController: Showable {
}
// In some code where you have viewController as UIViewController and you know
// that this object conforms to Showable protocol then you can do like this
guard let showable = viewController as? Showable {
return
}
showable.show()