关于如何使用代码触发 UIButton的Unwind Segue
当我们在一个控制视图上,在UITextField输入文字信息之后,希望可以使用键盘的Done触发一个 Done的UIButton,但是刚开始我直接在
-(BOOL)textFieldShouldReturn:(UITextField *)textField 内调用按键的行为: - (IBAction)DonePhotoButton:(UIButton *)sender {
//代码 } 虽然可以执行到{}内的代码,但是不会触发按键按下之后一个Unwind Segue(解散当前视图,退回上一个视图,并完全一个方法),也就是说没有触发退回上一个视图然后再执行一个AddPhoto:方法,寻思着,为什么没有触发Unwind Segue,于是仔细查看最终找到了解决办法。
IPhone 上的视图:
在Storyboard里的unwind Segue:
我这里的代码是使用
[self performSegueWithIdentifier:kUNWIND_ID sender:nil];
强制执行一个带Identifier的Segue,并且判断是否符合要求,实验证明这是可行的
执行的代码:
- (IBAction)DonePhotoButton:(UIButton *)sender { }//按键事件 #pragma mark - prepareForSegue //prepare -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:kUNWIND_ID]) { NSManagedObjectContext * context = self.photographyerTakingPhoto.managedObjectContext; if (context) { Photo * photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:context]; photo.title = self.TextFieldTitle.text; photo.subtitle = self.TextFieldSubTitle.text; photo.whoTook = self.photographyerTakingPhoto; photo.latitude = [NSNumber numberWithDouble:self.location.coordinate.latitude]; photo.longitude = [NSNumber numberWithDouble:self.location.coordinate.longitude]; photo.imageURL = [self.imageURL absoluteString]; photo.thumbnailURL = [self.thumnailURL absoluteString]; self.photo = photo; } } } //判断identifer 决定是否执行prepareForSegue 同时给出警告 -(BOOL) shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{ if ([identifier isEqualToString:kUNWIND_ID]) { if (!self.image) { [self alert:@"No Photo taken!"]; return NO; }else if(![self.TextFieldTitle.text length] || ![self.TextFieldSubTitle.text length]){ [self.TextFieldTitle.text length] ? [self alert:@"SubTitle required!"] : [self.TextFieldSubTitle.text length] ? [self alert:@"Title required!"] : [self alert:@"Title and SubTitle required"] ; return NO; }else{ return YES; } }else{ return [super shouldPerformSegueWithIdentifier:identifier sender:sender]; } } //----------------------------------------------------------------// //点击键盘的return取消键盘 -(BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; BOOL CanSegue = [self shouldPerform:kUNWIND_ID]; if (CanSegue) [self performSegueWithIdentifier:kUNWIND_ID sender:nil]; return YES; } -(BOOL) shouldPerform:(NSString *)identifier { if ([identifier isEqualToString:kUNWIND_ID]) { if (!self.image) { [self alert:@"No Photo taken!"]; return NO; }else if(![self.TextFieldTitle.text length] || ![self.TextFieldSubTitle.text length]){ [self.TextFieldTitle.text length] ? [self alert:@"SubTitle required!"] : [self.TextFieldSubTitle.text length] ? [self alert:@"Title required!"] : [self alert:@"Title and SubTitle required"] ; return NO; }else{ return YES; } }else{ return NO; } }