我有一个 UIViewController
,然后当我长按 self.view
时,它会弹出一个弹出窗口 (MenuViewController
)。但是当我尝试通过 removeFromSuperview
删除弹出窗口时,它仍然出现
你可以通过这个 http://www.youtube.com/watch?v=nVVgmeJEnnY 查看我的问题的更多细节
ViewController.m
#import "MenuViewController.h"
@interface ViewController () {
MenuViewController *menu;
}
....
- (void)viewDidLoad
{
....
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(albumButtonPressed : ) name:@"albumButtonPressed" object:nil];
....
}
....
-(void)albumButtonPressed : (NSNotification*) notification {
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:photoPicker animated:YES];
}
...
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer {
menu = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
if (self.imageView.image != nil) {
menu.imageAdded = YES;
}
[self.view addSubview:menu.view];
}
MenuViewController.m
-(IBAction)albumButtonPressed:(id)sender {
[self.view removeFromSuperview];
[[NSNotificationCenter defaultCenter] postNotificationName:@"albumButtonPressed" object:nil];
}
最佳答案
抛开我对未应用适当的 View Controller 包含的保留,问题是您的 handleLongPress
将被多次调用,具有不同的 recognizer.state
值,一次是 UIGestureRecognizerStateBegan
和 UIGestureRecognizerStateEnded
。您应该检查手势的状态,例如:
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded) {
menu = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
if (self.imageView.image != nil) {
menu.imageAdded = YES;
}
[self.view addSubview:menu.view];
}
}
原答案:
我建议使用 removeFromSuperview
在您的代码处放置一个 NSLog
或断点,然后查看您是否能访问到那段代码。
这里有一些明显的问题。具体来说,您没有在 handleLongPress
中正确添加与 MenuViewController
关联的 View 。如果你想要一个带有它自己的 Controller 的 subview ,你必须使用包含(并且只适用于 iOS 5 和更高版本)。在遏制中,你有像 addChildViewController
这样的关键方法。等。参见 Creating Custom Container View Controllers在 View Controller Programming Guide 或查看 WWDC 2011 - Implementing UIViewController Containment .顺便说一句,您还维护了对 MenuViewController
的强引用,因此即使您成功删除了它的 View ,也会泄露 Controller 。
花一点时间浏览一下收容文档/视频,我想您会想重新审视一下您是如何展示菜单的。这是密集阅读,但值得真正理解。遏制很强大,但必须正确实现。
关于ios - UIViewController removeFromSuperview 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14049682/