How to create a round button?

前端 未结 10 1528
刺人心
刺人心 2020-12-02 09:33

I want to create a round circular button. This button should look like a circle.

This code gives round rectangular button.

UIButton *button = [UIBut         


        
相关标签:
10条回答
  • 2020-12-02 09:58
    UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
    myButton.frame = CGRectMake(50,50,30,30);
    [myButton addTarget:self action:@selector(buttonEvent) forControlEvents:UIControlEventTouchUpInside];
    [myButton setImage:[UIImage imageNamed:@"sarabjit.png"] forState:UIControlStateNormal];
    [self.view addSubView:myButton];
    
    0 讨论(0)
  • 2020-12-02 09:58

    make a

    [UIButton buttonWithType:UIButtonTypeCustom];
    

    and try to use the corner radius property

       button.layer.cornerRadius = button.bounds.size.width/2 / 2.0
    
    0 讨论(0)
  • 2020-12-02 09:59

    Try this, it worked for me. It will make your button or any view in circular shape only if you have taken it in square i.e width should be equals to height.

    yourButton.layer.cornerRadius = yourButton.bounds.size.width/2;
    
    0 讨论(0)
  • 2020-12-02 10:08

    Tested Code:

    .h

     #import <QuartzCore/QuartzCore.h>
    
    -(void)roundButtonDidTap:(UIButton*)tappedButton;
    

    .m

    #define ROUND_BUTTON_WIDTH_HEIGHT YourButtonWidthToBeSetHere
    
    -(void)roundButtonDidTap:(UIButton*)tappedButton{
    
        NSLog(@"roundButtonDidTap Method Called");
    
    }
    
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setImage:[UIImage imageNamed:@"TimoonPumba.png"] forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(roundButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
    
    //width and height should be same value
    button.frame = CGRectMake(0, 0, ROUND_BUTTON_WIDTH_HEIGHT, ROUND_BUTTON_WIDTH_HEIGHT);
    
    //Clip/Clear the other pieces whichever outside the rounded corner
    button.clipsToBounds = YES;
    
    //half of the width
    button.layer.cornerRadius = ROUND_BUTTON_WIDTH_HEIGHT/2.0f;
    button.layer.borderColor=[UIColor redColor].CGColor;
    button.layer.borderWidth=2.0f;
    
    [self.view addSubview:button];
    

    Result

    enter image description here

    Geometry in this concept

    enter image description here

    0 讨论(0)
提交回复
热议问题