Swift-如何仅将下拉阴影应用于UIButton底部阴影,而不应用于其图像和标题标签?

时间:2018-11-05 03:40:33

标签: ios swift uibutton uikit

我正在尝试向UIButton添加投影,但我只希望UIButton底部阴影具有阴影,而不是其图像和标题。我关注了UIButton bottom shadow,但没有成功。 基本上,这就是我现在所拥有的: enter image description here

这就是我想要的东西: enter image description here

这是我当前的代码:

<link rel="stylesheet" type="text/css" href="css_file_url_here">

请帮助。预先感谢。

3 个答案:

答案 0 :(得分:1)

Check output in Attached image

在代码行下方签出

btn.setImage(UIImage(named: "Unknown.jpg"), for: .normal)

    btn.imageView?.layer.shadowColor = UIColor.blue.cgColor

    btn.imageView?.layer.shadowOffset = CGSize(width: 1, height: 1)

    btn.imageView?.layer.shadowOpacity = 1.0

    btn.imageView?.layer.shadowRadius = 5

    btn.imageView?.layer.masksToBounds = false

    btn.setTitle("    hello", for: .normal)

    btn.titleLabel?.layer.shadowColor = UIColor.black.cgColor

    btn.titleLabel?.layer.shadowOffset = CGSize(width: 1, height: 1)

    btn.titleLabel?.layer.shadowOpacity = 1.0

    btn.titleLabel?.layer.shadowRadius = 3

    btn.titleLabel?.layer.masksToBounds = false

    btn.backgroundColor = UIColor.red

答案 1 :(得分:0)

您最想为透明按钮应用阴影的最佳方法,您只需要将按钮嵌入视图中并在该视图上应用阴影效果即可。

就像我在下面所做的那样:

yourButtonView.layer.borderWidth = 0.5

yourButtonView.layer.borderColor = UIColor.gray.cgColor

yourButtonView.layer.shadowColor = UIColor.black.cgColor

yourButtonView.layer.shadowOffset = CGSize(width: 0, height: 2)

yourButtonView.layer.shadowOpacity = 1.0

yourButtonView.layer.shadowRadius = 0

yourButtonView.layer.masksToBounds = false

答案 2 :(得分:0)

请使用以下扩展名创建阴影

extension UIView {

func addshadow(top: Bool,
               left: Bool,
               bottom: Bool,
               right: Bool
               ) {

    let shadowRadius: CGFloat = 2.0
    self.layer.masksToBounds = false
    self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    self.layer.shadowRadius = shadowRadius
    self.layer.shadowOpacity = 0.3
    let path = UIBezierPath()
    var x: CGFloat = 0
    var y: CGFloat = 0
    var viewWidth = self.frame.width
    var viewHeight = self.frame.height
    if (!top) {
        y+=(shadowRadius+1)
    }
    if (!bottom) {
        viewHeight-=(shadowRadius+1)
    }
    if (!left) {
        x+=(shadowRadius+1)
    }
    if (!right) {
        viewWidth-=(shadowRadius+1)
    }
    path.move(to: CGPoint(x: x, y: y))
    path.addLine(to: CGPoint(x: x, y: viewHeight))
    path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
    path.addLine(to: CGPoint(x: viewWidth, y: y))
    path.close()
    self.layer.shadowPath = path.cgPath
}

}

使用-

    button.addshadow(top: false, left: false, bottom: true, right: false)