ios - OBJC @selector 在另一个实现中不起作用

标签 ios objective-c

int alert()
{
    //Alerting
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"0%" message:nil preferredStyle:UIAlertControllerStyleAlert];

    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 50.0F, 50.0F)];
    
    UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sampleButton setFrame:CGRectMake(0,5,60.0F, 40.0F)];
    [sampleButton setBackgroundImage:[UIImage systemImageNamed:@"terminal.fill"] forState:UIControlStateNormal];

    [sampleButton addTarget:[[MyObject alloc] init] action:@selector(showTerminal) forControlEvents:UIControlEventTouchDown];
    
    [customView addSubview:sampleButton];

    [alert.view addSubview:customView];

    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    });
}

@implementation MyObject

-(void)showTerminal
{
    NSLog(@"Terminal opened!");
}

@end

当从另一个@implementation调用函数时,如何使@selector工作!

我已经尝试过这段代码,但该函数从未执行“[sampleButton addTarget:[[MyObject alloc] init] action:@selector(showTerminal) forControlEvents:UIControlEventTouchDown];”

有人可以帮我解决这个问题,或者告诉我一个不涉及使用 ViewController() 的解决方法吗?

最佳答案

addTarget 不保留,因此您的对象被释放。您可以使用类对象和方法来检索事件

[sampleButton addTarget:[MyObject class] action:@selector(showTerminal) forControlEvents:UIControlEventTouchDown];

和:

+ (void)showTerminal

关于ios - OBJC @selector 在另一个实现中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77057514/

相关文章:

objective-c - 访问 Objective C 中的公共(public)字段

iphone - 更新数据并在 UITableView iOS 上显示

objective-c - 如何从 SKShapeNode 裁剪出 SKLabelNode?

ios - xcode 8 beta 中的主要 Storyboard错误

ios - 在 iOS 上启动带有视频的 youtube 应用程序

ios - 为 MBProgressHUD 添加完成回调

ios - uiview的圆角看起来不太好,uiview

ios - 在 View Controller 之间传递数据

ios - 如何快速访问字典数组

ios - 使用 YUV 颜色空间将 CMSampleBufferRef 转换为 UIImage?