UIView with shadow, rounded corners and custom drawRect

前端 未结 16 1436
南旧
南旧 2020-12-02 05:22

I have to create a custom UIView that will have round corners, a border, a shadow and its drawRect() method is overridden to provide custom drawing

16条回答
  •  误落风尘
    2020-12-02 05:55

    I wrote a small extension to UIView to manage both rounded corners AND drop shadow. As the variables are @IBInspectable, everything can be set directly in the storyboard !

    //
    //  UIView extensions.swift
    //
    //  Created by Frédéric ADDA on 25/07/2016.
    //  Copyright © 2016 Frédéric ADDA. All rights reserved.
    //
    
    import UIKit
    
    extension UIView {
    
        @IBInspectable var shadow: Bool {
            get {
                return layer.shadowOpacity > 0.0
            }
            set {
                if newValue == true {
                    self.addShadow()
                }
            }
        }
    
        @IBInspectable var cornerRadius: CGFloat {
            get {
                return self.layer.cornerRadius
            }
            set {
                self.layer.cornerRadius = newValue
    
                // Don't touch the masksToBound property if a shadow is needed in addition to the cornerRadius
                if shadow == false {
                    self.layer.masksToBounds = true
                }
            }
        }
    
    
        func addShadow(shadowColor: CGColor = UIColor.black.cgColor,
                   shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0),
                   shadowOpacity: Float = 0.4,
                   shadowRadius: CGFloat = 3.0) {
            layer.shadowColor = shadowColor
            layer.shadowOffset = shadowOffset
            layer.shadowOpacity = shadowOpacity
            layer.shadowRadius = shadowRadius
        }
    }
    

    And this is how it looks in the storyboard :

    The result :

    There is one requirement : DON'T touch either clipToBounds on the view (in code or in IB) or masksToBound on the layer.

    NB: one case in which it won't work : tableViews. As UITableView automatically triggers clipToBoundsunder the hood, we can't have a drop shadow.

    EDIT: as Claudia Fitero aptly noticed, you need to leave a small padding around the view to which you are adding a shadow, otherwise the shadow won't be visible. A 2px-padding is enough generally (depending on your shadow radius).

提交回复
热议问题