func drawCube() { let cube = UIView() cube.frame.origin.x = 40 cube.frame.origin.y = 500 cube.frame.size.width = 40 cube.frame.size.height = 40 cube.backgroundColor = UIColor.blue view.addSubview(cube) } 

Function with the original parameters of the cube. Numeric values ​​are not significant, this is just for example. If possible, I would like to understand the main points of the algorithm, so please leave a comment on the function.

  • it's not entirely clear what you need. For example, if based on 5 cubes, write a cycle of 5-4-3-2-1? - Max Mikheyenko
  • For example, if there are 5 cubes in the base, then in the row above 4, even higher than 3, and so on, and the cubes on the row above should be shifted, so as to form a uniform “Christmas tree”. - Hakeem
  • I'm in the development for Iyos not a boom boom, but there seems to be elementary logic. Draw a cycle of your squares by shifting the point to the right on the side of the square. When the cycle draws them draw above indented half the side of the square. There is a cycle in a cycle. In general, everything is easy. - Flippy
  • Would be able to write under apples c led code - Flippy
  • Thank you, the logic I understand myself, only recently began to learn the swift, for me at the moment is a problem to display it in the code) - Hakeem

1 answer 1

Far from optimal, but as a starting point should go

 class ViewController: UIViewController { let foundation = 5 let bottomLeft = CGPoint(x:40,y:200) let cubeSize = CGSize(width: 40, height: 40) override func viewDidLoad() { for i in stride(from: foundation, to: 0, by: -1) { print(i) for j in 0...i-1 { let coordX = Int(bottomLeft.x)+j*Int(cubeSize.width)+Int(cubeSize.width)/2*(foundation-i) let coordY = Int(bottomLeft.y)+i*Int(cubeSize.height) self.drawCube(coordinate: CGPoint(x: coordX, y: coordY)) } } } func drawCube(coordinate:CGPoint) { let cube = UIView() cube.frame.origin.x = coordinate.x cube.frame.origin.y = coordinate.y cube.frame.size.width = self.cubeSize.width cube.frame.size.height = self.cubeSize.height cube.backgroundColor = UIColor.blue cube.layer.borderWidth = 1 cube.layer.borderColor = UIColor.black.cgColor view.addSubview(cube) } } 
  • Thank you for your answer, if not difficult could you comment on the work cycle? And what needs to be changed in the code so that the foundation would be random? When I try to set it to random Xcode starts swearing. Thanks in advance) - Hakeem
  • the inner one draws one row of cubes, the outer one is responsible for the rows and how many cubes in each - Max Mikheyenko