Fading UILabel in from left to right - ios

I want to animate a UILabel to fade text in from left to right. My code below fades the entire UILabel in at once, but I would like to go letter by letter or word by word. Also, words can be added to this text, and when that happens I only want to fade in the new words, not the entire UILabel again.
__weak ViewController *weakSelf = self;
weakSelf.label.alpha = 0;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^{ weakSelf.label.alpha = 1;}
completion:nil];

I have done this once before with decent results. You will probably have to tweak it to your preference.
First step is to create a gradient image to match the way you want the text to fade in. If your text color is black you can try this.
- (UIImage *)labelTextGradientImage
{
CAGradientLayer *l = [CAGradientLayer layer];
l.frame = self.label.bounds;
l.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0] CGColor], (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor], nil];
l.endPoint = CGPointMake(0.0, 0.0f);
l.startPoint = CGPointMake(1.0f, 0.0f);
UIGraphicsBeginImageContext(self.label.frame.size);
[l renderInContext:UIGraphicsGetCurrentContext()];
UIImage *textGradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return textGradientImage;
}
That code creates an black image that should fade from left to right.
Next, when you create you label, you need to set its text color based from a pattern made from the image we just generated.
self.label.alpha = 0;
self.label.textColor = [UIColor colorWithPatternImage:[self labelTextGradientImage]];
Assuming that works, the last step is to animate the label into view and change its text color while that happens.
[UIView transitionWithView:self.label duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
self.label.textColor = [UIColor blackColor];
self.label.alpha = 1;
} completion:^(BOOL finished) {
}];
The animation code is a little funky because the UILabel's textColor property doesn't seem to be animatable with a UIViewAnimation.

Well, I know how I would do it. I would make a mask containing a gradient, and animate the mask across the front of the label.
Here's the result when I do that (don't know whether it's exactly what you have in mind, but perhaps it's a start):

I managed to achieve this and created a function within a UIView extension:
#discardableResult public func addSlidingGradientLayer(withDuration duration: Double = 3.0, animationDelegate delegate: CAAnimationDelegate? = nil) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor, UIColor.clear.cgColor]
gradientLayer.startPoint = CGPoint(x: -1.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
let gradientAnimation = CABasicAnimation(keyPath: "startPoint")
gradientAnimation.fromValue = gradientLayer.startPoint
gradientAnimation.toValue = gradientLayer.endPoint
gradientAnimation.duration = duration
gradientAnimation.delegate = delegate
gradientLayer.add(gradientAnimation, forKey: "startPoint")
layer.mask = gradientLayer
return gradientLayer
}
To begin with we create a CAGradientLayer instance that we use as a mask for a view (in this case a UILabel).
We then create a CABasicAnimation instance, which we use to animate the startPoint of the CAGradientLayer. This has the effect of sliding the startPoint from left to right with some supplied duration value.
Finally, we an also the delegate of the CABasicAnimation. Then, if we adhere to the CAAnimationDelegate protocol, we can execute some code after the animation completes.
This is how you might use this extension:
class ViewController: UIViewController {
#IBOutlet weak var someLabel: UILabel!
private func configureSomeLabel() {
someLabel.text = "Sliding into existence!"
someLabel.sizeToFit()
someLabel.addSlidingGradientLayer(withDuration: 3.0, animationDelegate: self)
}
override func viewDidLoad() {
super.viewDidLoad()
configureSomeLabel()
}
}
Where someLabel has been hooked up to your storyboard. And as we've assigned this view controller as the animation delegate we need to add:
extension ViewController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
someLabel.layer.mask = nil
}
}
where I have chosen to remove the masking layer.
Hope this helps someone!

Related

Create gradient-based UICollectionViewCell background colour

I want to create custom bar for displaying some progress, that must look something like this:
So, as you can see each bar has it's own gradient background. I want to use UICollectionView for this. But problem is to create gradient background for each individual cell. So is it possible somehow create ONE basic gradient for whole UICollectionView, and then mask it, to be visible inside UICollectionViewCell?
Okay, here is the example, background is the gradient layer with different colours are spread and above you can create a mask layer to appear only on the rectangular shapes, which gives the illusion of the different rectangular layers having different gradient, you can play with gradient to get your desired effect,
First you subclass the UIView or you can create directly, better you can create a subclass as I am doing in the example
obj-c
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self createGreadient];
}
return self;
}
//this create a grenadine with the rectangular mask layer
- (void)createGreadient
{
UIColor *theColor = [UIColor redColor];//[[UIColor alloc] initWithRed:146.0/255.0 green:146.0/255.0 blue:146.0/255.0 alpha:1];
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
//u can add your own colours to get your requirement
gradientLayer.colors = [NSArray arrayWithObjects:
(id)[theColor CGColor],
(id)[[theColor colorWithAlphaComponent:0.7f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.4f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.3f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.2f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.1f] CGColor],
(id)[[UIColor clearColor] CGColor],nil];
[self.layer addSublayer:gradientLayer];
CAShapeLayer *layerMask = [[CAShapeLayer alloc] init];
layerMask.frame = self.bounds;
UIBezierPath *rectangularMaskPath = [self getRectangularMaskPathForCount:5];
layerMask.path = rectangularMaskPath.CGPath;
gradientLayer.mask = layerMask;
}
//this creates rectangular path, u can adjust the rectangular and u can
//pass different number of count as the progress proceeds
- (UIBezierPath *)getRectangularMaskPathForCount:(NSInteger)rectCount
{
UIBezierPath *path = [[UIBezierPath alloc] init];
int i = 0;
for(;i <= rectCount; i++)
{
UIBezierPath *aPath;
CGRect aRect = CGRectMake(20+ (i * 20), 20, 10, 100); //set the rectangular position to your requirement
aPath = [UIBezierPath bezierPathWithRect:aRect];
[path appendPath:aPath];
}
return path;
}
swift version
subclass the UIView and past the below code,
override init (frame : CGRect) {
super.init(frame : frame)
createGreadient()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createGreadient()
{
let color:UIColor = UIColor.red
let greadetLayer = CAGradientLayer.init()
greadetLayer.frame = self.bounds
greadetLayer.colors = [color.withAlphaComponent(0.8).cgColor,color.withAlphaComponent(0.7),color.withAlphaComponent(0.4).cgColor,color.withAlphaComponent(0.3).cgColor,color.withAlphaComponent(0.2),color.withAlphaComponent(0.1).cgColor]
self.layer .addSublayer(greadetLayer)
let rectangularMaskPath = self.creatrRectangularPathWithCount(countRect: 5)
let maskLayer:CAShapeLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = rectangularMaskPath.cgPath
greadetLayer.mask = maskLayer
}
func creatrRectangularPathWithCount(countRect:NSInteger) -> UIBezierPath {
let path : UIBezierPath = UIBezierPath()
for i in 0..<countRect {
let aPath = UIBezierPath.init(rect: CGRect(x: 20 + (i * 20), y:20, width: 10, height: 100))
path.append(aPath)
}
return path
}
You can use the above view like below,
in ViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let customView:CustomView = CustomView(frame: CGRect(x: 20, y: 20, width: 300, height: 300))
self.view.addSubview(customView)
}

How to animate (fade) UILabel textColor in Swift?

UIView.animateWithDuration(self.fadeTime, delay: 0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { [weak self] () -> Void in
var randomIndex = Int(arc4random_uniform(UInt32(CONSTANTS.MainColorScheme.count)))
self?.startButton.titleLabel!.textColor = CONSTANTS.MainColorScheme[randomIndex]
}) { (stuff Bool) -> Void in
}
This doesn't seem to work...it just "jumps" to the next color. It doesn't fade.
However, if I apply the same approach to self.view.backgroundColor, my code works.
Is there an alternative?
UILabel.textColor does not support animation. But you can animate CATextLayer:
Swift:
let textLayer = CATextLayer()
textLayer.string = "Your text"
textLayer.foregroundColor = yourFirstColor
textLayer.frame = yourButton.bounds
yourButton.layer.addSublayer(textLayer)
UIView.animateWithDuration(1) {
textLayer.foregroundColor = yourSecondColor
}
Objective C:
CATextLayer *textLayer = [CATextLayer layer];
[textLayer setString:#"Your text"];
[textLayer setForegroundColor:yourFirstColor];
[textLayer setFrame:yourButton.bounds];
[[yourButton layer] addSublayer:textLayer];
[UIView animateWithDuration:1 animations:^{
textLayer.foregroundColor = yourSecondColor;
}];
Indeed, the UIView.animateWithDuration will work with UILabel backgroundColor, while for the textColor it won't because color doesn't animate with UIView animations. Then, how to achieve?
Solution 1:
You can go for CATextLayer instead of a UILabel and then animate the color. For objective-C you can refer to this - iPad: Animate UILabels color changing
Solution 2:
You can use NSTimer and decrease the UILabel alpha as the time passes
Solution 3:
Or simply you can go for "FadeIn - FadeOut" animation with UIView.transitionWithView
Try this..
UIView.transitionWithView(YOURLABEL, duration: 0.325, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
// animation...
}, completion: { (fininshed: Bool) -> () in
// completion...
})
Also check for other syntax here
Cheers! :)

Fade edges of UITableView

I've made a little research about my problem and unfortunately there was no solution for my problem.
The closest was Fade UIImageView as it approaches the edges of a UIScrollView but it's still not for me.
I want my table to apply an "invisibility gradient" on the top. If the cell is at a 50px distance from the top edge it starts to vanish. The closer it is to the upper edge, the more invisible the part is. The cells height is about 200 pixels, so the lower part of the cell need to be visible in 100%. But nevermind - I need a table view (or table view container) to do this task, because similar tables can display other cells.
If the table is a subview of a solid color view, I can achieve that by adding an image which is a horizontal gradient that I can streach to any width. The top pixel of that image starts with the exact color of the background, and going down the same color has less alpha.
But...
we have a UITableView with transparent color. Below the table there is no solid color, but a pattern image/texture, that can also be different on other screens of the app.
Do you have any Idea how I can achieve this behaviour?
Regards
I took this tutorial and made some changes and additions:
It now works on all tableviews - even if they are part of bigger screen.
It works regardless of the background or whatever is behind the tableview.
The mask changes depends on the position of the table view - when scrolled to top only the bottom faded, in when scrolled to bottom only top is faded...
1. Start by importing QuartzCore and setting a mask layer in your controller:
EDIT: No need for reference to CAGradientLayer in class.
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface mViewController : UIViewController
.
.
#end
2. Add this to viewWillAppear viewDidLayoutSubviews:
(See #Darren's comment on this one)
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
if (!self.tableView.layer.mask)
{
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.locations = #[[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.2],
[NSNumber numberWithFloat:0.8],
[NSNumber numberWithFloat:1.0]];
maskLayer.bounds = CGRectMake(0, 0,
self.tableView.frame.size.width,
self.tableView.frame.size.height);
maskLayer.anchorPoint = CGPointZero;
self.tableView.layer.mask = maskLayer;
}
[self scrollViewDidScroll:self.tableView];
}
3. Make sure you are a delegate of UIScrollViewDelegate by adding it in the .h of your controller:
#interface mViewController : UIViewController <UIScrollViewDelegate>
4. To finish, implement scrollViewDidScroll in your controller .m:
#pragma mark - Scroll View Delegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGColorRef outerColor = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
CGColorRef innerColor = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
NSArray *colors;
if (scrollView.contentOffset.y + scrollView.contentInset.top <= 0) {
//Top of scrollView
colors = #[(__bridge id)innerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
} else if (scrollView.contentOffset.y + scrollView.frame.size.height
>= scrollView.contentSize.height) {
//Bottom of tableView
colors = #[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)innerColor];
} else {
//Middle
colors = #[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
}
((CAGradientLayer *)scrollView.layer.mask).colors = colors;
[CATransaction begin];
[CATransaction setDisableActions:YES];
scrollView.layer.mask.position = CGPointMake(0, scrollView.contentOffset.y);
[CATransaction commit];
}
Again: most of the solution is from this tutorial in cocoanetics.
This is a translation of Aviel Gross's answer to Swift
import UIKit
class mViewController: UIViewController, UIScrollViewDelegate {
//Emitted boilerplate code
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.tableView.layer.mask == nil {
//If you are using auto layout
//self.view.layoutIfNeeded()
let maskLayer: CAGradientLayer = CAGradientLayer()
maskLayer.locations = [0.0, 0.2, 0.8, 1.0]
let width = self.tableView.frame.size.width
let height = self.tableView.frame.size.height
maskLayer.bounds = CGRect(x: 0.0, y: 0.0, width: width, height: height)
maskLayer.anchorPoint = CGPoint.zero
self.tableView.layer.mask = maskLayer
}
scrollViewDidScroll(self.tableView)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
var colors = [CGColor]()
if scrollView.contentOffset.y + scrollView.contentInset.top <= 0 {
colors = [innerColor, innerColor, innerColor, outerColor]
} else if scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height {
colors = [outerColor, innerColor, innerColor, innerColor]
} else {
colors = [outerColor, innerColor, innerColor, outerColor]
}
if let mask = scrollView.layer.mask as? CAGradientLayer {
mask.colors = colors
CATransaction.begin()
CATransaction.setDisableActions(true)
mask.position = CGPoint(x: 0.0, y: scrollView.contentOffset.y)
CATransaction.commit()
}
}
//Emitted boilerplate code
}
Swift version of #victorfigol's excellent solution:
class FadingTableView : UITableView {
var percent = Float(0.05)
private let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
private let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
override func awakeFromNib() {
super.awakeFromNib()
addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object is FadingTableView && keyPath == "bounds" {
initMask()
}
}
deinit {
removeObserver(self, forKeyPath:"bounds")
}
override func layoutSubviews() {
super.layoutSubviews()
updateMask()
}
func initMask() {
let maskLayer = CAGradientLayer()
maskLayer.locations = [0.0, NSNumber(value: percent), NSNumber(value:1 - percent), 1.0]
maskLayer.bounds = CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height)
maskLayer.anchorPoint = CGPoint.zero
self.layer.mask = maskLayer
updateMask()
}
func updateMask() {
let scrollView : UIScrollView = self
var colors = [CGColor]()
if scrollView.contentOffset.y <= -scrollView.contentInset.top { // top
colors = [innerColor, innerColor, innerColor, outerColor]
}
else if (scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height { // bottom
colors = [outerColor, innerColor, innerColor, innerColor]
}
else {
colors = [outerColor, innerColor, innerColor, outerColor]
}
if let mask = scrollView.layer.mask as? CAGradientLayer {
mask.colors = colors
CATransaction.begin()
CATransaction.setDisableActions(true)
mask.position = CGPoint(x: 0.0, y: scrollView.contentOffset.y)
CATransaction.commit()
}
}
}
This is my version of the fading table view by inheriting UITableView. Tested for iOS 7 & 8.
There is no need to implement scrollViewDidScroll, layoutSubviews can be used instead.
By observing for bounds changes, the mask is
always properly placed when the rotation changes.
You can use the percent parameter to change how much fading you want at the edges, I
find a small value looking better in some cases.
CEFadingTableView.m
#import "CEFadingTableView.h"
#interface CEFadingTableView()
#property (nonatomic) float percent; // 1 - 100%
#end
#implementation CEFadingTableView
- (void)awakeFromNib
{
[super awakeFromNib];
self.percent = 5.0f;
[self addObserver:self forKeyPath:#"bounds" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if(object == self && [keyPath isEqualToString:#"bounds"])
{
[self initMask];
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:#"bounds"];
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self updateMask];
}
- (void)initMask
{
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.locations = #[#(0.0f), #(_percent / 100), #(1 - _percent / 100), #(1.0f)];
maskLayer.bounds = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
maskLayer.anchorPoint = CGPointZero;
self.layer.mask = maskLayer;
[self updateMask];
}
- (void)updateMask
{
UIScrollView *scrollView = self;
CGColorRef outer = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
CGColorRef inner = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
NSArray *colors = #[(__bridge id)outer, (__bridge id)inner, (__bridge id)inner, (__bridge id)outer];
if(scrollView.contentOffset.y <= 0) // top
{
colors = #[(__bridge id)inner, (__bridge id)inner, (__bridge id)inner, (__bridge id)outer];
}
else if((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height) // bottom
{
colors = #[(__bridge id)outer, (__bridge id)inner, (__bridge id)inner, (__bridge id)inner];
}
((CAGradientLayer *)scrollView.layer.mask).colors = colors;
[CATransaction begin];
[CATransaction setDisableActions:YES];
scrollView.layer.mask.position = CGPointMake(0, scrollView.contentOffset.y);
[CATransaction commit];
}
#end

Gradient mask on UIView

I have a UIView and want to have the bottom part of it fade out to 0 opacity.
May this be done to a UIView (CALayer) in order to affect an entire UIView and its content?
Yes, you can do that by setting CAGradientLayer as your view's layer mask:
#import <QuartzCore/QuartzCore.h>
...
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.frame = view.bounds;
maskLayer.colors = #[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
maskLayer.startPoint = CGPointMake(0.5, 0);
maskLayer.endPoint = CGPointMake(0.5, 1.0);
view.layer.mask = maskLayer;
P.S. You also need to link QuartzCore.framework to your app to make things work.
Using an Image as the mask to prevent Layout issues.
Although Vladimir's answer is correct, the issue is to sync the gradient layer after view changes. For example when you rotate the phone or resizing the view. So instead of a layer, you can use an image for that:
#IBDesignable
class MaskableLabel: UILabel {
var maskImageView = UIImageView()
#IBInspectable
var maskImage: UIImage? {
didSet {
maskImageView.image = maskImage
updateView()
}
}
override func layoutSubviews() {
super.layoutSubviews()
updateView()
}
func updateView() {
if maskImageView.image != nil {
maskImageView.frame = bounds
mask = maskImageView
}
}
}
Then with a simple gradient mask like this, You can see it even right in the storyboard.
Note:
You can use this class and replace UILabel with any other view you like to subclass.
🎁 Bones:
You can use any other shaped image as the mask just like that.

Why masksToBounds = YES prevents CALayer shadow?

With the following snippet, I'm adding a drop shadow effect to one my UIView. Which works pretty well. But as soon as I set the view's masksToBounds property to YES. The drop shadow effect isn't rendered any more.
self.myView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.myView.layer.shadowOpacity = 1.0;
self.myView.layer.shadowRadius = 10.0;
self.myView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.myView.layer.cornerRadius = 5.0;
self.myView.layer.masksToBounds = YES; // <-- This is causing the Drop shadow to not be rendered
UIBezierPath *path = [UIBezierPath bezierPathWithCurvedShadowForRect:self.myView.bounds];
self.myView.layer.shadowPath = path.CGPath;
self.myView.layer.shouldRasterize = YES;
Do you have any ideas on this?
Because shadow is an effect done outside the View, and that masksToBounds set to YES will tell the UIView not to draw anything that is outside itself.
If you want a roundedCorner view with shadow I suggest you do it with 2 views:
UIView *view1 = [[UIView alloc] init];
UIView *view2 = [[UIView alloc] init];
view1.layer.cornerRadius = 5.0;
view1.layer.masksToBounds = YES;
view2.layer.cornerRadius = 5.0;
view2.layer.shadowColor = [[UIColor blackColor] CGColor];
view2.layer.shadowOpacity = 1.0;
view2.layer.shadowRadius = 10.0;
view2.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
[view2 addSubview:view1];
[view1 release];
It's iOS 6 now, things might have changed. TheSquad's answer don't work for me until I managed to add one more line view2.layer.masksToBounds = NO;, otherwise shadow doesn't show. Although documentation says masksToBounds is NO by default, my code shows the opposite.
Here is how I make a rounded corner button with shadow, which is among the most commonly used code snippet in my app.
button.layer.masksToBounds = YES;
button.layer.cornerRadius = 10.0f;
view.layer.masksToBounds = NO; // critical to add this line
view.layer.cornerRadius = 10.0f;
view.layer.shadowOpacity = 1.0f;
// set shadow path to prevent horrible performance
view.layer.shadowPath =
[UIBezierPath bezierPathWithRoundedRect:_button.bounds cornerRadius:10.0f].CGPath;
[view addSubview:button];
EDIT
If views need to be animated or scrolled, masksToBounds = YES tax performance significantly, which means animation will probably get stuttered. To get rounded corner and shadow AND smooth animation or scrolling, use following code instead:
button.backgroundColor = [UIColor clearColor];
button.layer.backgroundColor = [UIColor redColor].CGColor;
button.layer.masksToBounds = NO;
button.layer.cornerRadius = 10.0f;
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:_button.bounds cornerRadius:10.0f].CGPath;
view.layer.shadowOffset = CGSizeMake(0.0f, 4.0f);
view.layer.shadowRadius = 2.0f;
view.layer.masksToBounds = NO;
view.layer.cornerRadius = 10.0f;
[view addSubview:button];
Swift 3.0 version with StoryBoard
The same idea with #TheSquad. Create a new view under the actual view and add shadow to the lower view.
1. Create a view under the actual view
Drag a UIView to StoryBoard with same constraint as your target view. Check clip to bound for the target view. Also make sure the new view is listed before the target view so that the target view will cover the new view.
2. Now link the new view to your code add add shadow on it
This is just a sample. You can do whatever way you want here
shadowView.layer.masksToBounds = false
shadowView.layer.shadowColor = UIColor.red.cgColor
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowOffset = CGSize(width: -1, height: 1)
shadowView.layer.shadowRadius = 3
shadowView.layer.shadowPath = UIBezierPath(rect: coverImage.bounds).cgPath
shadowView.layer.shouldRasterize = true
This is the Swift 3 and IBDesignable version of the answer posted by #TheSquad.
I used the same concept while making changes in the storyboard file. First I moved my targetView (the one which requires corner radius and shadow) inside a new containerView. Then I added the following lines of code (Reference: https://stackoverflow.com/a/35372901/419192) to add some IBDesignable attributes for UIView Class:
#IBDesignable extension UIView {
/* The color of the shadow. Defaults to opaque black. Colors created
* from patterns are currently NOT supported. Animatable. */
#IBInspectable var shadowColor: UIColor? {
set {
layer.shadowColor = newValue!.cgColor
}
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
else {
return nil
}
}
}
/* The opacity of the shadow. Defaults to 0. Specifying a value outside the
* [0,1] range will give undefined results. Animatable. */
#IBInspectable var shadowOpacity: Float {
set {
layer.shadowOpacity = newValue
}
get {
return layer.shadowOpacity
}
}
/* The shadow offset. Defaults to (0, -3). Animatable. */
#IBInspectable var shadowOffset: CGPoint {
set {
layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
}
get {
return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
}
}
/* The blur radius used to create the shadow. Defaults to 3. Animatable. */
#IBInspectable var shadowRadius: CGFloat {
set {
layer.shadowRadius = newValue
}
get {
return layer.shadowRadius
}
}
/* The corner radius of the view. */
#IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
After adding this code, I went back to the storyboard and on selecting my containerView I could now find a new set of attributes in the attributes inspector:
Other than adding values for these attributes as per my choice, I also added a corner radius to my targetView and set the masksToBounds property as true.
I hope this helps :)
I also had drastic performance issues with shadows and rounded corners. Instead of using the shadowPath part, I used the following lines which perfectly solved the performance hit:
self.layer.shouldRasterize = YES;
self.layer.rasterizationScale = UIScreen.mainScreen.scale;
Here is one of the solutions:
#IBOutlet private weak var blockView: UIView! {
didSet {
blockView.backgroundColor = UIColor.white
blockView.layer.shadowColor = UIColor.black.cgColor
blockView.layer.shadowOpacity = 0.5
blockView.layer.shadowOffset = CGSize.zero
blockView.layer.cornerRadius = 10
}
}
#IBOutlet private weak var imageView: UIImageView! {
didSet {
imageView.layer.cornerRadius = 10
imageView.layer.masksToBounds = true
imageView.layer.shouldRasterize = true
}
}

Resources