我有一个偶尔调用的方法。它创建一个按钮并给它一个框架并将其添加到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)];
}
有没有更好的方法来检测这个?
答案 0 :(得分:1)
CountNumberOfBluetoothDevices = CountNumberOfBluetoothDevices + 1;
更改为countNumberOfBluetoothDevices++;
[keys count]
代替keys.count
。CGRectMake(130, -200, 55,55)];
中的-200很奇怪,看起来你的视图层次结构存在一些问题。它为什么是否定的?而不是这个
NSArray *keys = [BluetoothDeviceDictionary allKeys];
for (NSUInteger k = keys.count; k > 0; k--) {
MCPeerID *key = keys[k - 1];
...
}
我愿意
for (MCPeerID *key in [bluetoothDeviceDictionary allKeys]) {
...
}