其他视图控制器中的swift override appdelegate方法
我在Appdelegate中编写了一个函数。我想在ViewcontrollerA,ViewcontrollerB中覆盖这个函数。因为相同的方法在ViewcontrollerA,ViewcontrollerB中具有不同的行为。其他视图控制器中的swift override appdelegate方法
如何在Viewcontroller中调用这个函数,我不明白。
更新
class NaviBarVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func click_save() {
}
}
class ViewcontrollerA: NaviBarVC {
override func viewDidLoad() { super.viewDidLoad() }
override func click_save() { // Error
super.click_save()
}
}
您不能覆盖该方法AppDelegate
。由于ViewController heirarchy没有将它的超类作为AppDelegate。它继承自UIViewController
。所以,如果你想覆盖,你必须创建一个的viewController类,并从这个类可以通过继承
像这种重写方法----
class BaseViewController : UIViewController{
func yourMethod(){
}
}
现在,类重写此方法会是这样的
class YourController : BaseViewController{
override func yourMethod(){
super.yourMethod()
// write your code here
}
}
是的,如果你只是想访问AppDelegate的方法,而不想重写它。你可以这样做。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.yourMethod()
@ swiftuser123你知道了吗? –
我试过了你的答案,但是它说方法不会从它的超类中重写方法。检查我更新的问题的代码。 – swiftuser123
@ swiftuser123检查我更新的答案。对不起,你的'YourController:UIViewController'类将是'class YourController:BaseViewController'。编辑您的代码。 –
不能覆盖,在AppDelegate中声明的功能,但您可以访问在AppDelegate中添加使用声明全局变量的函数。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
,您可以通过
appDelegate.yourFuncName...()
但我想改变它在我的Viewcontroller中的行为,这不可能吗? – swiftuser123
其实我在Appdelegate中创建了自己的导航栏,因为我想让这个导航栏出现在每个视图控制器中。保存按钮在这个导航栏中有一个动作。我想在其他视图控制器中调用此保存功能,并根据viewcontroller保存不同的值。 – swiftuser123
化妆类方法AppDelegate.h
@interface
+(AppDelegate*)Getdelegate;
-(void)testfunction;
AppDelegate.m
+(AppDelegate*)Getdelegate
{
return (AppDelegate*)[UIApplication sharedApplication].delegate;
}
在任何地方访问任何的viewController AppDelegate中的财产ViewControllerA
[[AppDelegate Getdelegate] testFunction];
问题是Swift – Shades
我不认为“覆盖”是你正在寻找的词。你的视图控制器肯定不是你的应用程序委托的子类? –
如果您想从您的视图控制器**调用**应用程序委托**的方法,请使用如下所示的内容:'if let appDelegate = UIApplication.delegate as? AppDelegate { appDelegate.myMethod()//改为你的实际方法 }' –
制作一个BaseViewController,然后用你的方法代替AppDelegate,然后从BaseViewController继承ViewControllerA和ViewControllerB。然后你可以重写该方法。 –