带有圆角和阴影的Swift uiview不起作用

时间:2016-10-26 15:40:34

标签: ios swift 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而不是子类中呢?

1 个答案:

答案 0 :(得分:3)

我会尝试将您的VC图层代码放在viewDidLayoutSubviews而不是viewDidLoad中。到那时,您的视图将适当调整大小。