我不确定我的代码是否有误,但编译时没有错误。
我有一个刷新按钮,它可以刷新 TableView,下面是代码:
- (IBAction)refreshButton:(UIButton *)sender {
UIButton *refreshButton = [UIButton alloc];
[refreshButton addTarget:self action:@selector(scanBLEDevices:) forControlEvents:UIControlEventTouchUpInside]; }
- (void)scanBLEDevices:(id)sender {
[manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:BLEService]] options:nil];
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(stopScan:) userInfo:nil repeats:NO];}
这段代码有没有错误?我不确定第二行是否允许:
UIButton *refreshButton = [UIButton alloc];
最佳答案
您的代码中没有“错误”,就像您所说的那样,它符合要求。这里的“错误”不仅仅是语法,而是上下文。
If you are expecting your button to fire and perform your scan, then you should be calling your method
scanBLEDevices:
inside yourIBAction
methodrefreshButton:
.
在您的代码片段中,通过在刷新按钮方法中创建一个新 UIButton
,您只是将一个操作分配给尚未初始化的按钮,并且不提供触发按钮的机会(它仅在该方法中创建和存在)。
假设您已在 Storyboard 中正确附加了操作方法,我建议将您的简单 IBAction
方法替换为以下内容:
- (IBAction)refreshButton:(UIButton *)sender {
[self scanBLEDevices:sender];
}
因为您的 scanBLEDevices:
方法需要一个 id
发送器,您可以传递您的按钮(因为毕竟您不在 BLE 方法中使用它,哈哈) .
希望这能帮助您指明正确的方向。编码愉快!
注意:如果您不确定此处允许allocation
的时间/地点,我建议阅读有关IBAction
的一些常见做法、目标和发件人(在代码中使用 UIButton
元素时)。
关于ios - 通过 UIButton 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732218/