gpt4 book ai didi

ios - 如何为 UIButton 传递目标参数?

转载 作者:行者123 更新时间:2023-11-28 21:59:18 25 4
gpt4 key购买 nike

我在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;
}

但是这个实现是错误的,因为我不知道如何从我的 ViewController 传递 target 参数?

在我的 viewController 中,我这样调用这个方法:

- (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];
}

最佳答案

您还需要在字典中传递目标(选择器将被调用的对象,在本例中是您调用 configuremoreviewwithbtns 方法的 View Controller )。所以你添加到数组中的字典将变成

@{@"title": @"thetitle", @"selector": NSStringFromSelector(@selector(theselector:)), @"target": self},

并且您必须将 UIView 扩展更改为:

[btn addTarget:confDict[@"target"]
action:NSSelectorFromString(confDict[@"selector"]
forControlEvents:UIControlEventTouchUpInside];

关于ios - 如何为 UIButton 传递目标参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com