简体   繁体   中英

How to align UIButtons within a circle?

Say for example I have 20 buttons. How can I add a subView of the UIView of this button in a circular format?

This will place the buttons around a circle of a given radius at a given center. It will also rotate each button using the transform property of UIView.

Hope it helps. :)

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *buttons = /* you buttons here */
    float curAngle = 0;
    float incAngle = ( 360.0/(buttons.count) )*PI/180.0;
    CGPoint circleCenter = CGPointMake(160, 200); /* given center */
    float circleRadius = 100; /* given radius */
    for (UIButton *button in buttons)
    {
        CGPoint buttonCenter;
        buttonCenter.x = circleCenter.x + cos(curAngle)*circleRadius;
        buttonCenter.y = circleCenter.y + sin(curAngle)*circleRadius;
        button.transform = CGAffineTransformRotate(button.transform, curAngle);
        button.center = buttonCenter;
        [self.view addSubview:button];

        curAngle += incAngle;
    }
}

Result:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM