2013-04-11 57 views
0

我想显示UIViewControllerMyViewController通过点击UICollectionViewCell然后关闭它。UIButton的IBAction错误

所以,在我didSelectItemAtIndexPath

CGRect myFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 
MyViewController *myController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; 
myController.view.frame = myFrame; 
[self.view addSubview:myController.view]; 

它的作品!

MyViewController我有UIButton链接到:

- (IBAction)close:(id)sender { 
    [self.view removeFromSuperview]; 
} 

但是当我点击该按钮,我有这个,而不是接近方法调用:

enter image description here

编辑:感谢calampunay and Manohar

问题已解决。但我已经更换两个addSubviewremoveFromSuperview到AppDelagate,其中宣布MyViewController作为属性。原因是 - 我想关闭MyViewController即使我会跳转到其他选项卡(我的TabBar在我的应用程序中)或其他东西。

这会更好,如果MyViewController将关闭,即使我在其他地方(不在其框架中)点击。

+0

你的对象被释放,我猜。检查强或保留。 – 2013-04-11 06:45:20

+0

[self.view removeFromSuperview];你的删除..然后扫管笏将被删除..你知道吗? – 2013-04-11 06:57:08

回答

0

申报.h文件中

MyViewController *myController; 

在.M

myController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; 
myController.view.frame = myFrame; 
[self.view addSubview:myController.view]; 

- (IBAction)close:(id)sender 
{ 
    [myController.view removeFromSuperview]; 
} 
+0

不理解。 ** addSubview **在根控制器中,但** removeFromSuperview **在MyController中。我应该在哪里申报? – Romowski 2013-04-11 06:52:13

+0

试试编辑答案 – 2013-04-11 07:15:01

+0

谢谢!看到我编辑的问题 – Romowski 2013-04-11 07:56:24

0

在您根/父视图控制器,声明为myController的财产:

@property (strong, nonatomic) MyViewController *mycontroller; 

在你didSelectItemAtIndexPath,请改为:

CGRect myFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 
self.myController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; 
myController.view.frame = myFrame; 
[self.view addSubview:myController.view]; 

的问题是,当按钮轻击动作发生的myController已经释放,并尝试调用close:方法来一个释放的对象(myController的)。

+0

谢谢!看到我编辑的问题 – Romowski 2013-04-11 07:56:51