Xamarin NSNotificatioCenter:我怎样才能通过NSObject?
我正在尝试使用NSNotificationCenter在我的应用程序中向另一个应用程序发布通知。 所以在我的目标类中,我创建我的观察者如下:
NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", delegate {ChangeLeftSide(null);});
我有我的方法:
public void ChangeLeftSide (UIViewController vc) { Console.WriteLine ("Change left side is being called"); }
现在从另一个UIViewController我发布通知如下:
NSNotificationCenter.DefaultCenter.PostNotificationName("ChangeLeftSide", this);
如何在目标类中访问在post通知中传递的视图控制器? 在iOS中它非常直接,但我似乎无法找到单声道(Xamarin)…
当您使用AddObserver
,您希望以稍微不同的方式执行此操作。 请尝试以下方法:
NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide);
并声明您的ChangeLeftSide
方法符合AddObserver
期望的Action
– 为您提供实际的NSNotification
对象。 :
public void ChangeLeftSide(NSNotification notification) { Console.WriteLine("Change left side is being called by " + notification.Object.ToString()); }
因此,当您使用PostNotificationName
,您将UIViewController对象附加到通知,该通知可以通过Object
属性在NSNotification
检索。
我找到了答案,以下是我在问题中发布的代码需要进行的更改:
public void ChangeLeftSide (NSNotification notification) { Console.WriteLine ("Change left side is being called"); NSObject myObject = notification.Object; // here you can do whatever operation you need to do on the object }
并且观察者被创建:
NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide);
现在你可以投射或输入检查NSObject并用它做任何事情! 完成!
上述就是C#学习教程:Xamarin NSNotificatioCenter:我怎样才能通过NSObject?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1005230.html