2

I am trying to keep border for UIButton.If i use the following code it's working.

Case:1

[[_myButton layer] setBorderWidth:1.0f];
[[_myButton layer] setBorderColor:[UIColor lightGrayColor].CGColor];

But before when i wrote:

self.baseTypeButton.layer.borderWidth=2.0f;
self.myButton.layer.borderColor=[UIColor lightGrayColor];

XCode proposed me to do

enter image description here

Now my code changed,but i failed to set border in this case:

Case:2

_myButton.layer.borderWidth=2.0f;
_myButton.layer.borderColor=(__bridge CGColorRef _Nullable)([UIColor lightGrayColor]);

I am not using Auto-layout. Can anybody explain what is the difference between case-1 and case-2. Why case-2 wont work.

UdayM
  • 1,725
  • 16
  • 34
  • did you add `#import ` framework ? – iVarun Apr 06 '16 at 06:14
  • @ivarun:QuartzCore framework is already added in my project – UdayM Apr 06 '16 at 06:21
  • 1
    UIColor is not CGColor. You can't bridge it. You might use this to save yor time https://github.com/AlexHsieh/ButtonAppearance – AlexHsieh Apr 06 '16 at 11:16
  • @AlexHsieh: really thankyou for your support. in your github link "AHButton.h" file is missing. – UdayM Apr 07 '16 at 06:20
  • @uday.m , there are 2 ways to use it. 1. use cocoapod or 2. you can just copy file from here https://github.com/AlexHsieh/ButtonAppearance/tree/master/Pod/Classes – AlexHsieh Apr 10 '16 at 06:56

3 Answers3

7

layer.borderColor must be CGColor, so code below will work.

_myButton.layer.borderWidth=2.0f;
_myButton.layer.borderColor=[ UIColor lightGrayColor ].CGColor;

Your code

   [UIColor lightGrayColor]

returns a UIColor instance, not a CGColor instance. And UIColor can't bridge to CGColor, so your cast

(__bridge CGColorRef _Nullable)

returns unexpected result.

You can see strange result using this code

NSLog( @"%@", (__bridge CGColorRef _Nullable)([UIColor lightGrayColor]) );

returning below. ( Xcode 7.3 )

2016-04-06 15:30:51.415 36442877[8570:2643221] UIDeviceWhiteColorSpace 0.666667 1

If you give borderColor CGColor instance directory, you don't need casting.

Satachito
  • 5,838
  • 36
  • 43
1

If you are using ARC in your project than,

_myButton.layer.borderWidth=2.0f;
_myButton.layer.borderColor=(__bridge CGColorRef _Nullable)([UIColor lightGrayColor]);

Will not work, because __bridge CGColorRef _Nullable will autorelease reference.the moment CFRelease() is called the object is gone and points to nothing.

And

[[_myButton layer] setBorderWidth:1.0f];
[[_myButton layer] setBorderColor:[UIColor lightGrayColor].CGColor];

will work as expected.

For more information check:

ARC and bridged cast

Community
  • 1
  • 1
Ronak Chaniyara
  • 5,335
  • 3
  • 24
  • 51
0

Use this code

_myButton.layer.borderWidth=2.0f;
_myButton.layer.borderColor=[UIColor lightGrayColor].CGColor;
Monika Patel
  • 2,287
  • 3
  • 20
  • 45