How to set rectangle border for custom type UIButton

前端 未结 6 509
臣服心动
臣服心动 2020-12-28 08:55

I am trying to set an image as the background of a custom UIButton. I was able to set a background image for the \"rounded rect\" UIButton in interface builder, but now the

相关标签:
6条回答
  • 2020-12-28 09:29

    I'd just like to add to the answers provided by nanshi and Jonathan.

    In order to access the border and cornerRadius properties of the layer you will first need to import the QuartzCore framework.

    #import <QuartzCore/QuartzCore.h>

    Otherwise you will not be able to access the properties.

    0 讨论(0)
  • 2020-12-28 09:34

    You can set the border properties on the CALayer by accessing the layer property of the button.

    First, add Quartz

    #import <QuartzCore/QuartzCore.h>
    

    Set properties:

    [[myButton layer] setBorderWidth:2.0f];
    [[myButton layer] setBorderColor:[UIColor greenColor].CGColor];
    
    0 讨论(0)
  • 2020-12-28 09:35

    You could also "User Defined Runtime Attributes" in IB to set rounded corners like done in image below.

    http://i.stack.imgur.com/uBkuB.png

    0 讨论(0)
  • 2020-12-28 09:44

    When you set a background image in a button, the button outlines go away. Include them in your image, if you need different sizes look at the UIImage

    stretchableImageWithLeftCapWidth:topCapHeight:

    method.

    0 讨论(0)
  • 2020-12-28 09:49

    Check out the cornerRadius, borderWidth and borderColor properties of CALayer. These properties are new as of iPhone OS 3.0.

    You probably want to subclass UIButton and then set these properties in the constructor. Your button has a layer property you can access to set these border properties.

    Here's an example:

    - (id)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
    
        [self.layer setBorderWidth:1.0];
        [self.layer setCornerRadius:5.0];
        [self.layer setBorderColor:[[UIColor colorWithWhite:0.3 alpha:0.7] CGColor]];
    }
    
    return self;
    }
    
    0 讨论(0)
  • 2020-12-28 09:50
        #import <QuartzCore/QuartzCore.h> // don't forget to add this in your file
        CALayer * layer = [yourUIButton layer];
        [layer setMasksToBounds:YES];
        [layer setCornerRadius:0.0]; //when radius is 0, the border is a rectangle
        [layer setBorderWidth:1.0];
        [layer setBorderColor:[[UIColor grayColor] CGColor]];
    

    i know this is an old question, but still i would like to post my answer here. since i was looking for answer but got this resolved myself in an easy way.

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