绘制圆网格

Draw grid of circles

在 iOS 上实现绘制具有固定列和行的圆网格的最佳方法是什么?。当用户点击它时,我想识别每个圆圈。 我尝试使用集合视图,但 CoreGraphics 似乎适用于此类任务。

您好,请检查以下代码。我连续添加了 3 个圆圈,如果你愿意,你可以使用更多。

   - (void)viewDidLoad {
        [super viewDidLoad];
        UIView *circleView;
        int x = 10;
        int y = 20;
        static int tagNum = 0;
        for (int row=0; row < 5;) {
            for (int cirNum =0 ; cirNum <3;) {

                circleView = [[UIView alloc] initWithFrame:CGRectMake(x,y,100,100)];
                circleView.alpha = 0.5;
                circleView.layer.cornerRadius = 50;
                circleView.backgroundColor = [UIColor blueColor];
                circleView.tag = tagNum;
                NSLog(@"tagNum is %d", tagNum);
                [self.view addSubview:circleView];

                cirNum ++;
                x = x + 100;
                tagNum ++;
                //y = y + 20;

            }
            row++;
            y = y + 100;
            x = 10;
        }
        // Do any additional setup after loading the view, typically from a nib.
    }


    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint location = [[touches anyObject] locationInView:self.view];
    CGRect fingerRect = CGRectMake(location.x-5, location.y-5, 10, 10);

    for(UIView *view in self.view.subviews){
        CGRect subviewFrame = view.frame;

        if(CGRectIntersectsRect(fingerRect, subviewFrame)){
            //we found the finally touched view
            //NSLog(@"Yeah !, i found it %@",view);
            NSLog(@"view tag touched is %ld",view.tag);

        }

    }

}

输出看起来像这样

您可以按如下方式动态创建按钮:

- (void)drawSheet
{
    int numberOfRow=5;
    int numberOfColumn=4;
    float x = 1,
            y = 20,
            padding = 5,
            width = (self.view.frame.size.width-(padding*(numberOfColumn-1)))/numberOfColumn,
            height = (self.view.frame.size.height-(padding*(numberOfRow-1)))/numberOfRow;
    int counter = 0;
    for (int i=0; i<numberOfRow; i++) {
        for (int j=0; j<numberOfColumn; j++) {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, 74, 74)];
            btn.layer.cornerRadius = btn.frame.size.width/2;
            btn.layer.borderColor = [UIColor grayColor].CGColor;
            btn.layer.borderWidth = 2.0;
            [btn addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
            btn.clipsToBounds = YES;
            btn.tag = counter;
            [self.view addSubview:btn];
            x = x + width + padding;
            counter = counter + 1;
        }
        x = 0;
        y = y + height + padding;
    }
}

当你点击它时,你会得到它的标签:

- (IBAction)buttonPress:(UIButton *)sender{
    NSLog(@"%ld",sender.tag);
}