-1

我有一个不时调用的方法。它创建一个按钮并给它一个框架并将其添加到 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)];
}

有没有更好的方法来检测这个?

4

1 回答 1

1
  1. 不要使用大写的变量和/或属性名称。
  2. 更改CountNumberOfBluetoothDevices = CountNumberOfBluetoothDevices + 1;countNumberOfBluetoothDevices++;
  3. 使用[keys count]而不是keys.count.
  4. -200 inCGRectMake(130, -200, 55,55)];很奇怪,看起来您的视图层次结构存在一些问题。为什么是负面的?
  5. 而不是这个

    NSArray *keys = [BluetoothDeviceDictionary allKeys];
    for (NSUInteger k = keys.count; k > 0; k--) {
        MCPeerID *key = keys[k - 1];
        ...
    }
    

我会做

    for (MCPeerID *key in [bluetoothDeviceDictionary allKeys]) {
        ...
    }
于 2013-09-14T22:33:34.430 回答