How to create border in UIButton?

前端 未结 12 1514
天命终不由人
天命终不由人 2020-12-02 05:51

I use custom button in my app named \"addButton\" and I want to border it with white color how can i get the white color border around my custom button?

相关标签:
12条回答
  • 2020-12-02 06:21

    The problem setting the layer's borderWidth and borderColor is that the when you touch the button the border doesn't animate the highlight effect.

    Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.

    Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:

    Images.xcassets

    Then, you set it as the button's background image:

    Button properties

    If your image is a template image you can set tint color of the button and the border will change:

    Final Button

    Now the border will highlight with the rest of the button when touched.

    0 讨论(0)
  • 2020-12-02 06:24

    To change button Radius, Color and Width I set like this:

    self.myBtn.layer.cornerRadius = 10;
    self.myBtn.layer.borderWidth = 1;
    self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;
    
    0 讨论(0)
  • 2020-12-02 06:27

    You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

    Directly use:

    [[myButton layer] setBorderWidth:2.0f];
    [[myButton layer] setBorderColor:[UIColor greenColor].CGColor];
    
    0 讨论(0)
  • 2020-12-02 06:33

    And in swift, you don't need to import "QuartzCore/QuartzCore.h"

    Just use:

    button.layer.borderWidth = 0.8
    button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor
    

    or

    button.layer.borderWidth = 0.8
    button.layer.borderColor = UIColor.grayColor().cgColor
    
    0 讨论(0)
  • 2020-12-02 06:33

    Swift 5

    button.layer.borderWidth = 2
    

    To change the colour of the border use

    button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)
    
    0 讨论(0)
  • 2020-12-02 06:34

    Update with Swift 3

        button.layer.borderWidth = 0.8
        button.layer.borderColor = UIColor.blue.cgColor
    

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