如何等到调用委托按钮

时间:2013-03-12 10:14:07

标签: objective-c xcode4.5

我想创建一个显示UIActionSheet的函数,等到用户按下按钮然后按下按钮

@interface UIActionSheetHandler () <UIActionSheetDelegate>

@end
@implementation UIActionSheetHandler


-(NSInteger) buttonIndexWithMessage:(NSString *) title andArrayOfOptions:(NSArray *) options
{

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

    for (NSString * strOption in options) {
        [actionSheet addButtonWithTitle:strOption];
    }

    [actionSheet showInView:[BGMDApplicationsPointers window]];

    //Wait till delegate is called.
    return 0;//I want to return buttonIndex here.
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //What should I put it here
}
@end

如何制作//等到代表被召唤等待?哦,是的,我不希望主线程等待,但我想我可以解决这个问题。

2 个答案:

答案 0 :(得分:2)

我猜你误解了代表的概念。不能返回从buttonIndexWithMessage:andArrayOfOptions:

按下的按钮

事实上,UIActionSheet在那个时间点甚至都不可见。

按下按钮后,UIActionSheet将调用代理的actionSheet:clickedButtonAtIndex:方法。

因此,在您放入//What should I put it here there的位置,您将被移交已按下的按钮的索引。在那里你可以对按下的按钮作出反应。 例如:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog (@"Button pressed with index: %d", buttonIndex); 
}

答案 1 :(得分:1)

这个有效

self.operation=[NSOperationQueue new]; //These four line is necessary to suspend the whole thread.
self.operation.suspended=true; //Okay make t
[self.operation addOperationWithBlock:^{}];
[self.operation waitUntilAllOperationsAreFinished];//Don't get out of the function till user act.

然后在代表

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    self.buttonIndex=buttonIndex;
    self.operation.suspended=false;
}

注意:我仍在寻找更优雅的解决方案。