Swift - Problems with corner radius and drop shadow

前端 未结 14 1455
失恋的感觉
失恋的感觉 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 19:00

    If somebody need add shadows to rounded buttons in Swift 3.0, here is a good method to do it.

    func addShadowForRoundedButton(view: UIView, button: UIButton, shadowColor: UIColor, shadowOffset: CGSize, opacity: Float = 1) {
        let shadowView = UIView()
        shadowView.backgroundColor = shadowColor
        shadowView.layer.opacity = opacity
        shadowView.layer.cornerRadius = button.bounds.size.width / 2
        shadowView.frame = CGRect(origin: CGPoint(x: button.frame.origin.x + shadowOffset.width, y: button.frame.origin.y + shadowOffset.height), size: CGSize(width: button.bouds.width, height: button.bounds.height))
        self.view.addSubview(shadowView)
        view.bringSubview(toFront: button)
    }
    

    Use this method in func viewDidLayoutSubviews() as bellow:

    override func viewDidLayoutSubviews() {
        addShadowForRoundedButton(view: self.view, button: button, shadowColor: .black, shadowOffset: CGSize(width: 2, height: 2), opacity: 0.5)
    }
    

    The effect of this method is:

提交回复
热议问题