pengwang
pengwang

Reputation: 19956

replace delegate using block to pass value

I have read so many positive things about using blocks - in particular that it simplifys the code by elimanting delegate calls. I have found examples where blocks are used at end of animation instead of delegate calls. the block example is easy but i cannot use the example to the iphone app.for example i use the delegate:

.h

@protocol AWActionSheetDelegate <NSObject>

- (int)numberOfItemsInActionSheet;
- (AWActionSheetCell*)cellForActionAtIndex:(NSInteger)index;
- (void)DidTapOnItemAtIndex:(NSInteger)index;

@end

@interface AWActionSheet : UIActionSheet

   @property (nonatomic, assign)id<AWActionSheetDelegate> IconDelegate;
-(id)initwithIconSheetDelegate:(id<AWActionSheetDelegate>)delegate ItemCount:(int)cout;
@end

.m

- (void)actionForItem:(UITapGestureRecognizer*)recongizer
{

   [IconDelegate DidTapOnItemAtIndex:cell.index];

}

and i use it :

 -(void)DidTapOnItemAtIndex:(NSInteger)index
{
    NSLog(@"tap on %d",index);

}

how use block not use delegate i can get the index,can you give advice and if give good block category to finish the effect is very good . i donot want to use delegate to pass the index,i only want to use block to get the index

Upvotes: 0

Views: 257

Answers (2)

Matteo Gobbi
Matteo Gobbi

Reputation: 17707

Use this object:

https://github.com/matteogobbi/MGActionSheet

This is an easy example to init and use the object by block:

//Initialization
MGActionSheet *actionSheet = [[MGActionSheet alloc] initWithTitle:@"Block action sheet!" cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Option 1", @"Option 2", @"Option 3", nil];

//Show with completition block
[actionSheet showInView:self.view withChoiceCompletition:^(int buttonIndex) {

    if(buttonIndex == actionSheet.cancelButtonIndex) NSLog(@"Cancelled");
    else if(buttonIndex == actionSheet.destructiveButtonIndex) NSLog(@"Destructed");
    else {
        NSLog(@"Option at index: %d", buttonIndex);
    }
}];

Upvotes: 0

Odrakir
Odrakir

Reputation: 4254

I think you are looking for something like this:

//implementation for AWActionSheet's method: actionForItem:withBlock:

-(void) actionForItem:(UITapGestureRecognizer*)recongizer withBlock:(void(^)(NSInteger integer)) block {

    NSInteger myInt = 0;
    //whatever

    //callback
    block(myInt);
}

and the call

AWActionSheet* actionSheet;
[actionsheet actionForItem:recognizer withBlock:^(NSInteger integer) {
    NSLog(@"myInt: %d", integer);
}];

Upvotes: 1

Related Questions