如何通过按下第二个界面控制器(模态视图)中的按钮来删除第一个界面控制器中的一行

How to delete a row in the 1st Interface Controller by pressing a button in the 2nd Interface Controller ( Modal View )

我在第一个界面控制器中有一个 table,当按下一行时,会打开一个模态界面控制器,它包含一个按钮。

我想要按钮删除第一个界面控制器中的行。

这是我的代码:

在控制器第一个界面

Blockquote

   // It opens up a modal view ( with the context of the tapped row )

   override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
       var timelineRow = timeline.reverse()
       return timelineRow[rowIndex]

   }

Blockquote

这是我在第二个界面控制器中的代码

Blockquote

   override func awakeWithContext(context: AnyObject?) {
   super.awakeWithContext(context)

      sentContext = (context as? Dictionary)!
      sentRow = sentContext
      //sentRow contains the context 
   }


  @IBAction func deleteRow() {
     var sentRow : [String:String] = ["action":"delete"]   
     NSNotificationCenter.defaultCenter().postNotificationName("notification_DeleteRow", object: nil, userInfo: sentRow)    
     dismissController()
 }

Blockquote

我的问题:

在这种情况下有几种选择:

  1. 您可以使用 NSUserDefaults,虽然它可以工作,但这不是 class 的预期用途。
  2. 您可以创建自己的自定义 NSNotification 并从模态控制器广播它。您的第一个界面控制器将侦听此事件并删除相应的记录。
  3. 您可以将对第一个界面控制器的引用传递给模态控制器并在 awakeWithContext: 中检索它。这允许您将第一个界面控制器设置为委托。一旦发生这种情况,您可以定义任何协议来通知第一个控制器重要事件。

我有一个博客 post 详细介绍了后两个主题:Advanced WatchKit Interface Controller Techniques

这可以通过自定义委托轻松实现,

@protocol MyCustomDelegate <NSObject>

- (void)deleteButtonTapped:(id)sender;

@end

- (IBAction)deleteButtonTapped:(id)sender {
    if ([self.delegate respondsToSelector:@selector(deleteButtonTapped:)]) {
        [self.delegate deleteButtonTapped:sender];
    };
}

更详细的答案是here