是否可以在CornerRaduis
上同时放置UIView
和阴影?
我为UIView
设置了一个自定义类,该类使用@IBInspectable
来设置cornerRadius
和addShadow
,它们可以是true
或{{1 }}。当我设置false
时,阴影不会显示,如果我拿走cornerRadius
,则会再次显示阴影。预先感谢!
自定义类别:
cornerRadius
答案 0 :(得分:1)
我更喜欢扩展它,而不是每次都创建自定义分类和更改uiview的类。 我通过扩展UIView来实现这一点,如下所述:
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor.init(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = shadowRadius
}
}
@IBInspectable
var shadowOffset : CGSize{
get{
return layer.shadowOffset
}set{
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor : UIColor{
get{
return UIColor.init(cgColor: layer.shadowColor!)
}
set {
layer.shadowColor = newValue.cgColor
}
}
@IBInspectable
var shadowOpacity : Float {
get{
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
}
并将情节提要中的属性设置为:
就是这样。
希望这会有所帮助。
答案 1 :(得分:0)
在true
中设置masksToBounds
addShadow:Bool
,否则您无需在addShadow:Bool didSet方法中设置masksToBounds
@IBInspectable var addShadow:Bool = true{
didSet(newValue) {
if(newValue == true){
//self.layer.masksToBounds = false
self.layer.masksToBounds = true
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: 2, height: 3)
self.layer.shadowRadius = 3
self.layer.shadowPath = UIBezierPath(rect: bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
print("trying to use shadow")
}
}
}
https://spin.atomicobject.com/2017/07/18/swift-interface-builder/
答案 2 :(得分:0)
这是诀窍,在添加影子代码之前,您必须将 true
设置为 masksToBounds
,然后将 false
设置为 masksToBounds
。
您可以检查此方法以明确说明:
func addShadow(color: UIColor, bottomOrTop: Bool = false, radius: CGFloat = 2, height: CGFloat = 3) {
// These below line makes the trick to draw shadow with corner radius
self.layer.masksToBounds = true
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: height, height: bottomOrTop ? height : height * -1)
self.layer.shadowRadius = radius
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = 0.3
}