绘制圆圈网格

时间:2015-07-04 10:08:17

标签: ios core-graphics

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

2 个答案:

答案 0 :(得分:2)

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

- (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);
}

enter image description here

答案 1 :(得分:1)

嗨请检查以下代码。我连续添加了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);

        }

    }

}

输出看起来像这样

simulator image