Search code examples
arraysswiftfor-loopgrid-layout

Grid with points


I want to create grid with little circles 4 x 4

something like that :

enter image description here

I created the circle that will be used for the grid , but can't figure out how to create the grid with initializing the 4x4 grid with this circle

class PracticeView: UIView {
let box = UIView()

override func draw(_ rect: CGRect) {
    circles()
}

func circles() {
    let diameter = 10
    let centerCirclePath = UIBezierPath(ovalIn: CGRect(x:  Int(box.frame.size.width)  + 20 , y: Int(box.frame.size.height) + 20 , width: diameter, height: diameter))
    UIColor.black.setFill()
    centerCirclePath.fill()
   }
}

I think that I must make for-in loop in another for-in loop to create the grid and then somehow to initialize the circle somehow ,but I am not too sure because I`m new in swift.


Solution

  •  override func draw(_ rect: CGRect) {
        drawCirclesGrid()
    }
    
    func drawCirclesGrid() {
        let diameter: CGFloat = 10
        let points: CGFloat = 4 // number of points that are needed ( hard coded ! )
    
        let cellWidth = bounds.width / points
    
        let cellHeight = bounds.height  / points
    
        for i in 0..<Int(points) {
    
            for j in 0..<Int(points) {
    
                let circleX: CGFloat = ((CGFloat(i) + 0.5) * cellWidth)
    
                let circleY: CGFloat =  ((CGFloat(j) + 0.5) * cellHeight)
    
                let centerCirclePath = UIBezierPath(ovalIn: CGRect(x: circleX, y: circleY, width: diameter, height: diameter))
    
                let  customlayer = CAShapeLayer()
                customlayer.path = centerCirclePath.cgPath
                customlayer.fillColor = UIColor.black.cgColor
                layer.addSublayer(customlayer)
            }
        }