Ios 设置CALayer阴影如何打破自动布局约束?
我有cell的imageView阴影自定义:Ios 设置CALayer阴影如何打破自动布局约束?,ios,swift,autolayout,calayer,Ios,Swift,Autolayout,Calayer,我有cell的imageView阴影自定义: override func layoutSubviews() { moviePosterImageView.layer.shadowOffset = .zero moviePosterImageView.layer.shadowColor = UIColor.black.cgColor moviePosterImageView.layer.shadowRadius = 5 moviePosterImageView.la
override func layoutSubviews() {
moviePosterImageView.layer.shadowOffset = .zero
moviePosterImageView.layer.shadowColor = UIColor.black.cgColor
moviePosterImageView.layer.shadowRadius = 5
moviePosterImageView.layer.shadowOpacity = 1
moviePosterImageView.layer.masksToBounds = false
moviePosterImageView.layer.shadowPath = UIBezierPath(rect: moviePosterImageView.bounds).cgPath
}
但它打破了imageView的大小和限制。没有阴影,效果很好
在另一个swift文件中使用此代码,并在故事板或xib中轻松设置阴影
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 {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.borderColor = color.cgColor
} else {
layer.borderColor = nil
}
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
}
但它打破了imageView的大小和限制
是的,因为你忘了一开始就说
override func layoutSubviews() {
super.layoutSubviews() // important
由于自动布局发生在
layoutSubviews
中,如果不调用super
,则会阻止其运行 我打电话给super,但还是samei解决了我的问题,将imageView包装到一个容器中(仅视图)