一般情况下是否可以从其他 IntefaceController 调用扩展委托(delegate)中的方法?
类似于:
InterfaceController *interfaceController =[[InterfaceController alloc] init];
interfaceController callMethod
我的界面 Controller
#import "InterfaceController.h"
#import "OrdinaryEventRow.h"
#import <UIKit/UIKit.h>
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController()
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
//Configure interface objects here.
-(void)doSomething {
[self presentControllerWithName:@"goalView" context:nil];
}
@end
扩展代理:
#import "ExtensionDelegate.h"
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
#import "setGoal.h"
@implementation ExtensionDelegate
//Handle Local Notification Actions
-(void)handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UNNotification *)localNotification{
if([identifier isEqualToString:@"action"]){
//Setup WCSession
if ([WCSession isSupported]) {
[[WCSession defaultSession] setDelegate:self];
[[WCSession defaultSession] activateSession];
//Get the value from slider
NSString *someString = [[NSUserDefaults standardUserDefaults]
stringForKey:@"Update"];
NSString *Update = @"Update";
NSDictionary *applicationData = [[NSDictionary alloc] initWithObjects:@[Update] forKeys:@[@"Update"]];
//Send Message to the iPhone (handle over the goal value)
[[WCSession defaultSession] sendMessage:applicationData
replyHandler:^(NSDictionary *reply) {
//handle reply from iPhone app here
}
errorHandler:^(NSError *error) {
//catch any errors here
}
];
}
}
//If Goal Setting was clicked
if([identifier isEqualToString:@"action3"]){
//here I want to call doSomething from InterfaceController
}
}
所以我只想从 ExtensionDelegate 调用 InterfaceController 中定义的方法。
最佳答案
没有办法从ExtensionDelegate
初始化WKInterfaceController
并调用它的方法。如果您尝试调用方法的 Controller 是根 Controller ,您可以从 ExtensionDelegate
中的 WKExtension
获取 rootController
并将其转换为对其调用一个方法。
// Objective-C
if ([WKExtension shared].rootController isKindOfClass:[InitialInterfaceController class]) {
(InitialInterfaceController *)[WKExtension shared].rootController customMethod];
}
// Swift
if let root = WKExtension.shared().rootInterfaceController as? InitialInterfaceController {
root.customMethod()
}
* 我的 objective-c 有点生疏,所以如果那里有语法错误,请更新或在评论中让我知道,我可以编辑。
从您的代码示例中,您正尝试根据本地通知执行操作,因此最好的办法是在界面 Controller 本身中处理通知。取决于您使用的 watchOS
watch 操作系统 3
handleAction(withIdentifier:for:) reference
watch 操作系统 2
handleAction(withIdentifier:for:) reference
关于调用这些方法的重要说明,您的扩展委托(delegate)未实现 handleAction(withIdentifier:for:) 方法,WatchKit 在您应用的根接口(interface) Controller 上调用此方法以响应通知界面中的按钮点击。
关于ios - 扩展委托(delegate)中的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222145/