簡體   English   中英

陰影沒有出現 Swift 4.2

[英]Shadow is not appearing Swift 4.2

我正在嘗試快速為按鈕添加陰影。 我以編程方式在這個視圖控制器上創建了元素,我有一種感覺,這就是為什么沒有出現陰影的原因,因為陰影出現在我在應用程序中的其他視圖控制器中。 我也嘗試過處理 clipToBounds 和 maskToBounds 但無法修復它。 我錯過了什么?

這是我用來嘗試顯示陰影的代碼。

let dateLabelButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false

    button.layer.cornerRadius = 10
    button.backgroundColor = Colours().brightRedColour

    button.addTarget(self, action: #selector(segueToPopUp), for: .touchUpInside)

    let shadow = UIBezierPath(roundedRect: button.bounds, cornerRadius: 10).cgPath
    button.layer.shadowRadius = 5
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOpacity = 1
    button.layer.masksToBounds = false
    button.layer.shadowPath = shadow

    return button
}()

這是我添加到此按鈕的約束。

// Sets up layout for date label button
    dateLabelButton.bottomAnchor.constraint(equalTo: self.view.topAnchor, constant: self.view.frame.height * 2/3 - 50).isActive = true
    dateLabelButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
    dateLabelButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
    dateLabelButton.topAnchor.constraint(equalTo: barChart.bottomAnchor, constant: 10).isActive = true
    dateLabelButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

任何幫助都會很棒,我已經嘗試了幾個小時,但我無法弄清楚。

如果您使用UIBezierPath作為陰影,則需要在viewDidLayoutSubviews() ,如下所示:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let shadow = UIBezierPath(roundedRect: dateLabelButton.bounds, cornerRadius: 10).cgPath
    dateLabelButton.layer.shadowRadius = 5
    dateLabelButton.layer.shadowColor = UIColor.black.cgColor
    dateLabelButton.layer.shadowOpacity = 1
    dateLabelButton.layer.masksToBounds = false
    dateLabelButton.layer.shadowPath = shadow
}

否則,您可以像 Enea 的回答一樣注釋掉您的shadowPath

我認為這會奏效。

let dateLabelButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false

    button.layer.cornerRadius = 10
    button.backgroundColor = Colours().brightRedColour

    button.addTarget(self, action: #selector(segueToPopUp), for: .touchUpInside)

    //let shadow = UIBezierPath(roundedRect: button.bounds, cornerRadius: 10).cgPath
    button.layer.shadowRadius = 5
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
    button.layer.shadowOpacity = 1.0
    button.layer.masksToBounds = false
   // button.layer.shadowPath = shadow

    return button
}()

暫無
暫無

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

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