如何通过关闭按钮取消UIActionSheet并避免崩溃?

6

我在另一篇文章(如何关闭操作表)上读到,我可以使用

[actionSheet dismissWithClickedButtonIndex:0 animated:YES];

为了使用定义在中的关闭按钮,来关闭 uiactionsheet:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                         delegate:nil
                                                cancelButtonTitle:nil
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:nil];

[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;


[actionSheet addSubview:pickerView];
[pickerView release];

UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
closeButton.momentary = YES; 
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];


[actionSheet dismissWithClickedButtonIndex:0 animated:YES];


[closeButton release];


[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];

[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];

然而,我不确定将这行代码放在哪里,是否能解决我的问题:

然而,我不确定把这一行放在哪里可以解决我的问题。

[actionSheet dismissWithClickedButtonIndex:0 animated:YES]; 

此外,当我点击关闭按钮时,应用程序崩溃,并显示错误消息“PROGRAM RECEIVED ERROR MESSAGE SIGBRT”。我认为这两个问题有关。有人可以提供帮助吗?

1个回答

10

只需实现dismissActionSheet并在其中添加您的关闭消息。

dismissActionSheet方法可能如下所示:

-(void)dismissActionSheet {
   [sheet dismissWithClickedButtonIndex:0 animated:YES];
}

你没有定义方法-(void)dismissActionSheet:(id)sender吗?你在按钮的addTarget方法中定义了它。如果你告诉它选择器是dismissActionSheet:,那么你也必须编写一个;-)。在这个方法中,调用dismissWithClickedButtonIndex:animated:。--清楚了吗? - Mundi
谢谢你,Mundi。我差不多完成了。我已经实现了-(void)dismissActionSheet:(id) sender{ [sender dismissWithClickedButtonIndex:0 animated:YES]; } 但是,我确定在'dismissWithClickedButtonIndex'之前我不需要放置'sender'。我需要引用'actionSheet'。当它不是函数dismissActionSheet:的参数时,我该如何引用actionSheet? - Shaddy
对的。函数不知道发送者是什么类型(只知道id),所以你需要进行强制类型转换。请参考我回答的编辑部分。 - Mundi
Mundi,我尝试了你的建议并抱有希望。但是,它仍然会崩溃。发送者不是UIActionsheet而是按钮,对吗? - Shaddy
1
确实,最好的解决方案是在别处保留您的操作表的引用(将其放入.h文件中,并在创建时将其分配给它),而不是根本不使用发送方。 - Mundi
成功了... Mundi 你太棒了!只需创建一个实例变量 actionSheetRef 并将其赋值为 actionSheet 即可。 - Shaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接