我有一个不时调用的方法。它创建一个按钮并给它一个框架并将其添加到 self.view 上。问题是我不希望这些按钮重叠,所以我使用一个计数器(整数)来计算有多少。有时计数器出错 +-1 并且两个按钮出现重叠。
这是代码:
在我的.h
int CountNumberOfBluetoothDevices;
在他们中
- (void) browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info{
NSLog(@"%@", peerID.description);
CountNumberOfBluetoothDevices = CountNumberOfBluetoothDevices + 1;
NSArray *keys = [BluetoothDeviceDictionary allKeys];
for (NSUInteger k = keys.count; k > 0; k--) {
MCPeerID *key = keys[k - 1];
UIButton *btn = BluetoothDeviceDictionary[key];
if ([key.displayName isEqualToString:peerID.displayName]) {
[btn removeFromSuperview];
NSLog(@"REMOVE DOUBLE");
CountNumberOfBluetoothDevices--;
[BluetoothDeviceDictionary removeObjectForKey:key];
}
}
if (CountNumberOfBluetoothDevices == 1) {
BluetoothDeviceButton = [[UIButton alloc] initWithFrame:CGRectMake(130, -200, 55,55)];
}else if (CountNumberOfBluetoothDevices == 2){
BluetoothDeviceButton = [[UIButton alloc] initWithFrame:CGRectMake(240, -200, 55,55)];
}else if (CountNumberOfBluetoothDevices == 3){
BluetoothDeviceButton = [[UIButton alloc] initWithFrame:CGRectMake(130, -125, 55,55)];
}else if (CountNumberOfBluetoothDevices == 4){
BluetoothDeviceButton = [[UIButton alloc] initWithFrame:CGRectMake(240, -125, 55,55)];
}
有没有更好的方法来检测这个?