UIView with shadow, rounded corners and custom drawRect

前端 未结 16 1408
南旧
南旧 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:48

    In Swift 4.1. For making rounded corner of UIView I have created Extension of UIView as follow.

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var viewOuter: UIView!
        @IBOutlet weak var viewInner: UIView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            viewOuter.backgroundColor = UIColor.clear
            viewInner.roundCorners(15.0)
            viewOuter.addViewShadow()
        }
    }
    extension UIView {
        public func roundCorners(_ cornerRadius: CGFloat) {
            self.layer.cornerRadius = cornerRadius
            self.clipsToBounds = true
            self.layer.masksToBounds = true
        }
    
        public func addViewShadow() {
            DispatchQueue.main.asyncAfter(deadline: (.now() + 0.2)) {
                let shadowLayer = CAShapeLayer()
                shadowLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 15).cgPath
                shadowLayer.fillColor = UIColor.white.cgColor
    
                shadowLayer.shadowColor = UIColor.lightGray.cgColor
                shadowLayer.shadowPath = shadowLayer.path
                shadowLayer.shadowOffset = CGSize(width: 2.6, height: 2.6)
                shadowLayer.shadowOpacity = 0.8
                shadowLayer.shadowRadius = 8.0
                self.layer.insertSublayer(shadowLayer, at: 0)
            }
        }
    }
    

提交回复
热议问题