Swift - Problems with corner radius and drop shadow

前端 未结 14 1449
失恋的感觉
失恋的感觉 2020-11-28 18:35

I\'m trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I\

14条回答
  •  星月不相逢
    2020-11-28 18:55

    Exact solution for 2020 syntax

    import UIKit
    class ColorAndShadowButton: UIButton {
        override init(frame: CGRect) { super.init(frame: frame), common() }
        required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder), common() }
        private func common() {
            // UIButton is tricky: you MUST set the clear bg in bringup;  NOT in layout
            backgroundColor = .clear
            clipsToBounds = false
            self.layer.insertSublayer(backgroundAndShadow, below: layer)
        }
        
       lazy var colorAndShadow: CAShapeLayer = {
            let s = CAShapeLayer()
            // set your button color HERE (NOT on storyboard)
            s.fillColor = UIColor.black.cgColor
            // now set your shadow color/values
            s.shadowColor = UIColor.red.cgColor
            s.shadowOffset = CGSize(width: 0, height: 10)
            s.shadowOpacity = 1
            s.shadowRadius = 10
            // now add the shadow
            layer.insertSublayer(s, at: 0)
            return s
        }()
        
        override func layoutSubviews() {
            super.layoutSubviews()
            // you MUST layout these two EVERY layout cycle:
            colorAndShadow = bounds
            colorAndShadow = UIBezierPath(roundedRect: bounds, cornerRadius: 12).cgPath
        }
    }
    

    • Note that the very old top answer here is correct but has a critical error

    Note that UIButton is unfortunately quite different from UIView in iOS.

    • Due to a strange behavior in iOS, you must set the background color (which of course must be clear in this case) in initialization, not in layout. You could just set it clear in storyboard (but you usually click it to be some solid color simply so you can see it when working in storyboard.)

    In general combos of shadows/rounding are a real pain in iOS. Similar solutions:

    https://stackoverflow.com/a/57465440/294884 - image + rounded + shadows
    https://stackoverflow.com/a/41553784/294884 - two-corner problem
    https://stackoverflow.com/a/59092828/294884 - "shadows + hole" or "glowbox" problem
    https://stackoverflow.com/a/57400842/294884 - the "border AND gap" problem
    https://stackoverflow.com/a/57514286/294884 - basic "adding" beziers

提交回复
热议问题