簡體   English   中英

Swift-如何僅將下拉陰影應用於UIButton底部陰影,而不應用於其圖像和標題標簽?

[英]Swift - How to apply the drop shadow only on UIButton Bottom Shadow but not for its image and its title label?

我試圖將陰影添加到UIButton,但我只希望UIButton底部陰影不包含其圖像和標題。 我跟隨UIButton底部陰影,但是沒有用。 基本上,這就是我現在所擁有的: 在此處輸入圖片說明

這就是我想要的: 在此處輸入圖片說明

這是我當前的代碼:

button.layer.borderWidth = 0.5
button.layer.borderColor = UIColor.gray.cgColor
button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowOffset = CGSize(width: 0, height: 2)
button.layer.shadowOpacity = 1.0
button.layer.shadowRadius = 0
button.layer.masksToBounds = false

請幫忙。 提前致謝。

檢查附件圖像中的輸出

檢出以下代碼行

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

親愛的為透明按鈕應用陰影的最佳方法,您只需要在視圖中嵌入按鈕並將陰影效果應用到該視圖即可。

就像我在下面做的那樣:

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

請使用以下擴展名創建陰影

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM