基本上我的问题很简单,我的“ DNAParentViewController” UIViewController中有一个按钮属性,它是:
var doneButton: UIButton = {
let button = UIButton()
button.customizedButtonStyle(title: "Done", bgColor: .clear, titleColor: .white, isBold: false, titleFontSize: 15)
return button
}()
我有3个子类,名称是“ CharacteristicsViewController”,其他2个(名称无关紧要),它们继承了“ DNAParentViewController”,我想通过在每个不同子类的viewDidLoad中使用button.addTarget(self, action: #selector(goToNext), for: .touchUpInside)
来自定义和重写每个doneButton的click目标。但是,在对其中3个对象执行此操作之后,每个视图控制器中的goToNext都没有被触发。
我想要的是让他们在不同的子类中单击doneButton后可以去不同的地方,我该怎么办?谢谢。
这里是完整的代码片段,可轻松查看它们:
DNAParentViewController.swift:
class DNAParentViewController: UIViewController {
var doneButton: UIButton = {
let button = UIButton()
button.customizedButtonStyle(title: "Done", bgColor: .clear, titleColor: .white, isBold: false, titleFontSize: 15)
return button
}()
}
CharacteristicsViewController.swift(另两个相同):
class CharacteristicsViewController: DNAParentViewController {
override func viewDidLoad() {
super.viewDidLoad()
customizsGUI()
}
func customizsGUI() {
doneButton.addTarget(self, action: #selector(goToGrowthAreas), for: .touchUpOutside)
}
//MARK: - Action Handlers
@objc func goToGrowthAreas() {
print("lalalalalalalal")
navigationController?.pushViewController(GrowthAreasViewController(), animated: true)
}
}
我认为解决这个问题的更好方法是创建一个ExtensionClass
。创建一个新的swift文件,并将其命名为App+Extensions.swift
。现在,一旦创建定义,就为UIButton
创建扩展名。
import UIKit
extension UIButton {
func customizsGUI(vc: UIViewController) {
self.addTarget(self, action: #selector(goToGrowthAreas), for: .touchUpOutside)
}
@objc func goToGrowthAreas(vc: UIViewController) {
print("lalalalalalalal")
vc.navigationController?.pushViewController(GrowthAreasViewController(), animated: true)
}
}
这样,您可以在任何按钮上调用此函数,而不必担心Parent
和Sub
类。另外,还有几种传递VC
的方法,但是它将为您完成任务。