gpt4 book ai didi

ios - 将目标从类别添加到 UIButton

转载 作者:行者123 更新时间:2023-11-29 02:53:40 26 4
gpt4 key购买 nike

我正在实现一个创建自定义 UIAlertView 的函数。我用 category 扩展了 UIView,我正在创建我的方法,称为

- (void)showCustomAlertWithTitle:(NSString *)title andMessage:(NSString *)message

我想将选择器添加到我的自定义警报 View 中的按钮,但该选择器包含在我的 UIViewController 中。我应该将选择器移到类别中,还是以某种方式在 viewcontroller 中引用它?如果我将选择器移动到类别中,我将无法访问 navigationcontroller...

UIView+Category.m中:

- (void)showCustomAlertWithTitle:(NSString *)title andMessage:(NSString *)message 
{
UIView *alert = [[UIView alloc] initWithFrame:CGRectMake((self.frame.size.width/2)-100, (self.frame.size.height/2)-50, 200, 100)];
UIButton *confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(30,40, 50, 50)];
[confirmButton addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
[alert addSubview:confirmButton];
[self addSubview:alert];
}

MyViewController.m 中的选择器方法

- (IBAction)delete:(id)sender 
{
[[self.view viewWithTag:-7] removeFromSuperview];
self.navigationController.navigationBar.hidden = NO;
}

最佳答案

您遇到了类别的限制。您不能将实例变量添加到类别中的类,因此您没有一种干净的方法来保存指向呈现 View Controller 的指针。

我建议为您的类别添加一个新方法:

- (void) addButtonWithTitle: (NSString*) title 
target: (id) target
action: (SEL) action
forControlEvents: (UIControlEvents)controlEvents;

然后在该方法的实现中,使用传入的参数来创建和配置按钮。该方法包括目标、选择器和应触发操作的事件列表。

关于ios - 将目标从类别添加到 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24170800/

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