IOS开发之用位运算符记录多个button的坐标

来源:互联网 发布:c语言汉诺塔问题 编辑:程序博客网 时间:2024/06/03 06:23

我们都学过位操作,工作中我们用好位操作能够大大提高程序的效率,简单介绍一个我的运用的例子:

- (void)buttonClick:(id)sender {

    UIButton *button = (UIButton *)sender;

    int tag = button.tag;

    int x = (tag>>8) &0xF;

    int y = tag & 0x0F;

    NSLog(@"(%d, %d)", x, y);

}


- (void)initMap {

    for (int x=0; x<10; x++) {

        for (int y=0; y<10; y++) {

            UIButton *backgroundButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

            backgroundButton.frame = CGRectMake(15+y*29, 15+x*29, gridWidth, gridHeight);

            backgroundButton.tag = (x<<8)|y;   //x转化为二进制后左移8位,之后与y取活 

            [backgroundButton addTarget:selfaction:@selector(buttonClick:)forControlEvents:UIControlEventTouchUpInside];

            [self.viewaddSubview:backgroundButton];

        }

    }

}

位运算符C语言提供了六种位运算符:& 按位与,| 按位与,^ 按位异或,~ 取反,<< 左移;相关的运用就不一一介绍了,网上很多。

  >> 右移


原创粉丝点击