2011-03-02 33 views
1

我没有完全理解monotouch中的委托机制。任何人都可以帮助我理解这个概念吗?Monotouch:了解委托机制模式

问题很简单。我将尝试映射我在Monotouch中Objective C中完成的工作。

例如,假设我在MyController的Objective C中创建了UIPopoverController。在目标C的代码如下:

@interface MyController : UIViewController <UIPopoverControllerDelegate> { 
    // ... 
} 
// ... 
@end 

里面MyController我可以istantiate一个UIPopoverController如下所示:在委托使用

UIPopoverController *popover = // ... 
popover.delegate = self; 

和最后的方法。

那么,Monotouch呢?

通过这个代码,我可以istantiate延伸UIViewController特定TouchUpInside事件处理程序内的UIPopoverControllerMyController类:

popover = new UIPopoverController(new CustomController()); 
popover.PopoverContentSize = new SizeF(200f, 200f); 
popover.PresentFromRect(button.Frame, containerForButtonView, UIPopoverArrowDirection.Left, true); 

附:一个重要的方面是将popover引用作为成员类,而不是处理程序内的局部变量,因为monotouch GC工作正常!

预先感谢您。

+0

我的第一个解决方案有效。我已经实现了一个扩展了UIPopoverControllerDelegate的CustomPopoverController。然后我添加了popover.delegate该控制器的一个实例。是否有可能作为代表** MyController **或** CustomController **? – 2011-03-02 09:03:34

+0

您的解决方案看起来如何?我能看到的唯一事件是'DidDismiss'和'WillReposition' ......并不是那么多。 – testing 2014-11-25 10:23:35

回答

3

对于C#,这确实比MonoTouch本身更多。在MonoTouch中,UIPopoverControllerDelegate是一个类,而C#不允许多重继承,因此您无法使用Obj-C将代码一对一地翻译。有可能性,但一个更简单的方法(下面的代码编译,但显然是行不通的):

public class MyController: UIViewController { 
     public void mymethod(){ 
      var popover = new UIPopoverController(); 
      popover.DidDismiss += HandlePopoverDidDismiss; 
      popover.PopoverContentSize = new SizeF(200f, 200f); 
      popover.PresentFromRect(button.Frame, containerForButtonView, UIPopoverArrowDirection.Left, true); 
     } 

     void HandlePopoverDidDismiss (object sender, EventArgs e) 
     { 
      Console.WriteLine("Working!"); 
     } 
    } 
} 

正如你所看到的,你可以添加一个事件处理程序的酥料饼的DidDismiss事件,这将做什么你要。一般来说,在所有控件中的代理处理Obj-C中的所有事件都可以这样使用。你也可以写的方法直列,像这样:

popover.DidDismiss += delegate { 
    //dosomething 
}; 

希望这是你在找什么。

2

这并不回答你的问题,具体到你的UIPopovercontroller我想你会发现this link from the Monotouch Docs useful.它解释了Objective-C代表和C#代表与MonoTouch的区别。关于你的具体问题,我没有时间去匆匆测试一个快速的测试案例来完全理解它,但是我想我会发布这个链接,以便你能够在这段时间阅读某些内容!