在UIViewController中使用UIImagePickerController出现NSInvalidArgumentException
在某个
UIViewController
中出现了这个错误,以下是代码
@interface TestViewController : UIViewController <ICALViewDelegate, UIWebViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> { UIButton *_avatar; UIImagePickerController *_avatarPicker; } @end - (id)init { ... _avatar = [[UIButton alloc] initWithFrame:avatarRect]; [_avatar setBackgroundColor:[UIColor blackColor]]; [_avatar addTarget:self action:@selector(pickAvatar:) forControlEvents:UIControlEventAllTouchEvents]; [[self view] addSubview:_avatar]; _avatarPicker = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { [_avatarPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [_avatarPicker setMediaTypes:[UIImagePickerController availableMediaTypesForSourceType:[_avatarPicker sourceType]]]; } [_avatarPicker setDelegate:self]; [_avatarPicker setAllowsEditing:YES]; ... } - (void)pickAvatar:(id)sender { [self presentModalViewController:_avatarPicker animated:YES]; }
当点击
_avatar
这个按钮时会出现这个错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <TestViewController: 0x689b2d0>.' *** First throw call stack: (0x149c052 0x172ed0a 0x5ae98d 0x5af58c 0x5af5cc 0xfdbc 0x149dec9 0x4e55c2 0x4e555a 0x58ab76 0x58b03f 0x589290 0x58a49f 0x50aac0 0x50ac56 0x4f1384 0x4ef6cf 0x4ef004 0x4ef682 0x4e4a0f 0x227cfa9 0x14701c5 0x13d5022 0x13d390a 0x13d2db4 0x13d2ccb 0x227b879 0x227b93e 0x4e2a9b 0x1fa8 0x1f05 0x1) terminate called throwing an exception
似乎意思是不能从一个模态窗口再弹出另一个模态窗口,不知道如何解决这个问题。
AS001
11 years, 8 months ago
Answers
怀疑是
[self presentModalViewController:_avatarPicker animated:YES];
这个时候 _avatarPicker 没了
建议这样做
- (id)init { ... _avatar = [[UIButton alloc] initWithFrame:avatarRect]; [_avatar setBackgroundColor:[UIColor blackColor]]; [_avatar addTarget:self action:@selector(pickAvatar:) forControlEvents:UIControlEventAllTouchEvents]; [[self view] addSubview:_avatar]; ... } - (void)pickAvatar:(id)sender { if (nil == _avatarPicker) { _avatarPicker = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { [_avatarPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [_avatarPicker setMediaTypes:[UIImagePickerController availableMediaTypesForSourceType:[_avatarPicker sourceType]]]; } [_avatarPicker setDelegate:self]; [_avatarPicker setAllowsEditing:YES]; } [self presentModalViewController:_avatarPicker animated:YES]; }
Y肛互撸娃
answered 11 years, 8 months ago