我使用初始 ViewController 创建了一个作为单视图应用程序的项目;将 subViewController 添加到项目中。在两个视图控制器中都添加了带有平移手势的 UIImageView。
它在 viewController.m 中工作,但是当它被添加到 subViewController 并且子视图作为子视图添加到视图控制器中时,程序会因“Exc_bad_access”而崩溃。
任何人都有一些解决方案?
这是我的代码:
视图控制器.m
#import "ViewController.h"
#import "SubViewController.h"
//#define SUB
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
#ifdef SUB
SubViewController *sb = [[SubViewController alloc] init];
[self.view addSubview:sb.view];
#else
UIImageView* img_ = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"monkey_1.png"]];
img_.userInteractionEnabled = YES;
UIPanGestureRecognizer *stampPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[stampPanGesture setMinimumNumberOfTouches:1];
[stampPanGesture setMaximumNumberOfTouches:1];
[img_ addGestureRecognizer:stampPanGesture];
img_.center = self.view.center;
[self.view addSubview:img_];
#endif
}
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
子视图控制器.m
#import "SubViewController.h"
@interface SubViewController ()
@end
@implementation SubViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView* img_ = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"monkey_1.png"]];
img_.userInteractionEnabled = YES;
UIPanGestureRecognizer *stampPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[stampPanGesture setMinimumNumberOfTouches:1];
[stampPanGesture setMaximumNumberOfTouches:1];
[img_ addGestureRecognizer:stampPanGesture];
img_.center = self.view.center;
[self.view addSubview:img_];
}
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}