带点的网格

时间:2017-06-09 14:44:00

标签: arrays swift for-loop grid-layout

我想用小圆圈4 x 4

创建网格

类似的东西:

enter image description here

我创建了将用于网格的圆圈,但无法弄清楚如何使用此圆圈初始化4x4网格来创建网格

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

我认为我必须在另一个for-in循环中制作for-in循环来创建网格然后以某种方式以某种方式初始化圆圈,但我不太确定因为我是swift的新手。

1 个答案:

答案 0 :(得分:0)

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