Reputation: 10254
I write one category method in UIView+Extensions.m
:
@interface UIView (Extensions)
+ (UIView*)configureMoreViewWithBtns:(NSArray*)btnsConf;
@end
+ (UIView*)configureMoreViewWithBtns:(NSArray*)btnsConf
{
UIView* moreView = [[self alloc] initWithFrame:CGRectMake(195, 180, 120, 100)];
[moreView setBackgroundColor:[UIColor lightGrayColor]];
for (int i = 0; i < btns.count; i++) {
NSDictionary* confDict = btnsConf[i];
UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(0, i*30 + 10, 120, 20)];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[btn setTitle:confDict[@"title"] forState:UIControlStateNormal];
[btn addTarget:self
action:NSSelectorFromString(confDict[@"selector"]
forControlEvents:UIControlEventTouchUpInside];
[moreView addSubView:btn];
}
return moreView;
}
But this implement is wrong, because i don't know how pass target
parameter from my ViewController?
In my viewController, i called this method like this:
- (void)handleMoreImageTapped:(UITapGestureRecognizer*)gestureRecognizer
{
NSLog(@"%s", __FUNCTION__);
UITableViewCell* tappedCell = [UIView tableViewCellFromTapGestture:gestureRecognizer];
NSArray* btnsConf = @[
@{@"title": @"分享", @"selector": NSStringFromSelector(@selector(handleShare:))},
@{@"title": @"私信", @"selector": NSStringFromSelector(@selector(handleSiXin:))},
@{@"title": @"举报或屏蔽", @"selector": NSStringFromSelector(@selector(handleJuBao:))}
];
UIView* moreView = [UIView configureMoreViewWithBtns:btnsConf];
}
Upvotes: 0
Views: 205
Reputation: 361
You need to also pass the target (the object the selector would be called on, in this case the viewcontroller from which you call the configuremoreviewwithbtns
method) in the dictionairies.
So a dictionairy you add to the array would become
@{@"title": @"thetitle", @"selector": NSStringFromSelector(@selector(theselector:)), @"target": self},
and you'd have to change the UIView extension to this:
[btn addTarget:confDict[@"target"]
action:NSSelectorFromString(confDict[@"selector"]
forControlEvents:UIControlEventTouchUpInside];
Upvotes: 2