2012-07-17 10 views
5

Tengo un montón de visitas en mi aplicación. Me gustaría organizarlos en forma circular y cambiar su centro en función de la cantidad de vistas presentes.iOS - Organizar subvistas en forma circular

Por lo tanto, si hay 3 vistas, se verían como un triángulo, pero seguirían formando un círculo. Si hay 4, se vería como un cuadrado, pero seguiría formando un círculo, y así sucesivamente ...

En resumen, los centros de todas las vistas se ubicarían en un círculo imaginario.

¿Alguna sugerencia?

Respuesta

13

Este es el código que utilicé en uno de mis proyectos, espero que ayude.

// you must set both of these 
CGPoint centerOfCircle; 
float radius; 

int count = 0; 
float angleStep = 2.0f * M_PI/[arrayOfViews count]; 

for (UIView *view in arrayOfViews) { 
    float xPos = cosf(angleStep * count) * radius; 
    float yPos = sinf(angleStep * count) * radius; 
    view.center = CGPointMake(centerOfCircle.x + xPos, centerOfCircle.y +yPos); 
    count++; 
} 
+0

Funciona muy bien .. !! – Shailesh

0

Puede dividir los grados de un círculo (360 grados o 2π radianes) por el número de vistas que tenga, luego ajuste sus centros según el ángulo y la distancia desde el centro.

Estas son algunas de las funciones que utilizo:

// These calculate the x and y offset from the center by using the angle in radians 
#define LengthDir_X(__Length__,__Direction__) (cos(__Direction__)*__Length__) 
#define LengthDir_Y(__Length__,__Direction__) (sin(__Direction__)*__Length__) 

// I use this to convert degrees to radians and back if I have to 
#define DegToRad(__ANGLE__) (((__ANGLE__) * 2.0 * M_PI)/360.0) 
#define RadToDeg(__ANGLE__) (((__ANGLE__) * 360)/(2.0 * M_PI)) 
0

Aquí hay una versión Swift 3 de la respuesta aceptada, como una extensión UIView con el offset argumentos:

public extension UIView { 
    public func distributeSubviewsInACircle(xOffset: CGFloat, yOffset: CGFloat) { 
     let center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) 
     let radius: CGFloat = self.bounds.size.width/2 
     let angleStep: CGFloat = 2 * CGFloat(Double.pi)/CGFloat(self.subviews.count) 
     var count = 0 
     for subview in self.subviews { 
      let xPos = center.x + CGFloat(cosf(Float(angleStep) * Float(count))) * (radius - xOffset) 
      let yPos = center.y + CGFloat(sinf(Float(angleStep) * Float(count))) * (radius - yOffset) 
      subview.center = CGPoint(x: xPos, y: yPos) 
      count += 1 
     } 
    } 
} 
Cuestiones relacionadas