Although it’s very simple, I often forget how to add a shadow in iOS using Objective-C. It’s not so much that I forget, but that there are certain required parameters that need to be set in order for it to work.
So I’ll post some examples here.
Using CALayer on a UILabel (Should work with any UIView subclass):
self.lblChampionName.layer.shadowOffset = CGSizeMake(0, 3); //default is (0.0, -3.0)
self.lblChampionName.layer.shadowColor = [UIColor blackColor].CGColor; //Default value is opaque black.
self.lblChampionName.layer.shadowRadius = 1.0; //default is 3.0
self.lblChampionName.layer.shadowOpacity = .5; //default is 0.0
Important Notes:
- CALayer’s
shadowColor
property takes a CGColor not a UIColor. You can convert UIColor to CGColor using UIColor’sCGColor
property as shown above. shadowOpacity
defaults to0.0
, if you don’t set it, you will not see your shadow.
Check the CALayer documentation for more information on the default values and their types.
Adding to a UIButton:
Adding to a UILabel without CALayer:
Adding to a UIButton without CALayer.
Adding drop shadow to a UIView.
If you want to add a drop shadow to a UIView (not a text shadow) you can apply the same CALayer approach as detailed in the first example.
Tidying up
Usually if you have one drop shadow (or text shadow) you want more. We can tidy up and centralize that using a Category in objective-c. See also: Programming with Objective-C: Customizing Existing Classes.
In Xcode 6, select File > New > Objective-C File then select Category as your file type. I named mine DropShadow
. Type UIView under Class. This creates the appropriate UIView+DropShadow
files.
This is what my code looks like:
UIView+DropShadow.h:
And the implementation file,
UIView+DropShadow.m:
and a sample invocation:
It’s ultimately the same amount of lines—if you are hard line wrapping like I am—however now we have autocompletion and tabbing.
The next step would be to add some sensible defaults and convenience methods. I added one to our new category, for example:
And now I can add shadows like this:
Learn more about const CGStruct and the possible caveats of using the initializer list.
If you wanted to, you could probably add some sort of class methods to change the defaults, that way you could on a per-project basis change your default shadow arguments without too much trouble. But I won’t go into that for now.
blog comments powered by Disqus