Swift - Problems with corner radius and drop shadow

前端 未结 14 1465
失恋的感觉
失恋的感觉 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:36

    To improve PiterPan's answer and show a real shadow (not just a background with no blur) with a circular button in Swift 3:

    override func viewDidLoad() {
        super.viewDidLoad()
        myButton.layer.masksToBounds = false
        myButton.layer.cornerRadius = myButton.frame.height/2
        myButton.clipsToBounds = true
    }
    
    override func viewDidLayoutSubviews() {
        addShadowForRoundedButton(view: self.view, button: myButton, opacity: 0.5)
    }
    
    func addShadowForRoundedButton(view: UIView, button: UIButton, opacity: Float = 1) {
        let shadowView = UIView()
        shadowView.backgroundColor = UIColor.black
        shadowView.layer.opacity = opacity
        shadowView.layer.shadowRadius = 5
        shadowView.layer.shadowOpacity = 0.35
        shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
        shadowView.layer.cornerRadius = button.bounds.size.width / 2
        shadowView.frame = CGRect(origin: CGPoint(x: button.frame.origin.x, y: button.frame.origin.y), size: CGSize(width: button.bounds.width, height: button.bounds.height))
        self.view.addSubview(shadowView)
        view.bringSubview(toFront: button)
    }
    

提交回复
热议问题