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/