我已经阅读了很多关于使用块的积极信息 - 特别是它通过调用委托调用来简化代码。我找到了在动画结束时使用块而不是委托调用的示例。块示例很简单但我不能将该示例用于iphone app.for示例我使用委托:
·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];
}
我用它:
-(void)DidTapOnItemAtIndex:(NSInteger)index
{
NSLog(@"tap on %d",index);
}
如何使用block不使用委托我可以得到索引,你能给出建议并且如果给出好的块类别来完成效果非常好。我不想使用委托来传递索引,我只想用block来获取索引
答案 0 :(得分:1)
我认为你正在寻找这样的东西:
//implementation for AWActionSheet's method: actionForItem:withBlock:
-(void) actionForItem:(UITapGestureRecognizer*)recongizer withBlock:(void(^)(NSInteger integer)) block {
NSInteger myInt = 0;
//whatever
//callback
block(myInt);
}
和电话
AWActionSheet* actionSheet;
[actionsheet actionForItem:recognizer withBlock:^(NSInteger integer) {
NSLog(@"myInt: %d", integer);
}];
答案 1 :(得分:0)
使用此对象:
https://github.com/matteogobbi/MGActionSheet
这是一个简单的初始化和逐块使用对象的例子:
//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);
}
}];