0
我試圖添加圓角和陰影到我UIView:斯威夫特UIView的圓角和陰影不起作用
myView.layer.cornerRadius = 2
myView.layer.masksToBounds = false
myView.layer.shadowColor = UIColor.black.cgColor
myView.layer.shadowOffset = CGSize(width: 0, height: 1)
myView.layer.shadowOpacity = 0.4
myView.layer.shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 2).cgPath
但是,這將讓陰影很遠拖放到右側和底部哪些是錯的。
我將在viewDidLoad中(),因爲我已經有另外一個子類我UIView這個代碼,所以我要添加陰影的VC,而不是在子類中
但是,如果我把代碼中的一個子類它的工作:
import UIKit
public class ShadowView: UIView {
open var cornerRadius: CGFloat = 2
open var shadowOffsetWidth: Int = 0
open var shadowOffsetHeight: Int = 2
open var shadowColor: UIColor? = UIColor.black
open var shadowOpacity: Float = 0.4
override open func layoutSubviews() {
layer.cornerRadius = cornerRadius
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
layer.masksToBounds = false
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight)
layer.shadowOpacity = shadowOpacity
layer.shadowPath = shadowPath.cgPath
}
}
但我怎麼能使其與放置在我的主VC的代碼,而不是一個子類工作?
我會嘗試把你的VC層代碼放在viewDidLayoutSubviews而不是viewDidLoad中。您的看法將根據該點適當調整大小。 –
(在旁註中,我禁不住注意到你的ShadowView代碼沒有調用super.layoutSubviews) –
@JoshuaKaden代碼來自這個回購:https://github.com/NathanWalker/MaterialCard,爲什麼必須我打電話super.layoutSubviews? – user2636197