Reputation: 1783
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
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.
Upvotes: 2
Views: 5095
Reputation: 2375
Use this code
_myButton.layer.borderWidth=2.0f;
_myButton.layer.borderColor=[UIColor lightGrayColor].CGColor;
Upvotes: 0
Reputation: 5888
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.
Upvotes: 7
Reputation: 5436
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:
Upvotes: 1