问题
I have a UIView
and I set a shadowPath
for it like this:
func addShadow() {
let cornerRadius: CGFloat = self.containerView.frame.height/2
self.containerView.layer.shadowPath = UIBezierPath(roundedRect: self.containerView.frame, cornerRadius: cornerRadius).cgPath
self.containerView.layer.shadowRadius = cornerRadius
self.containerView.layer.shadowOffset = .zero
self.containerView.layer.shadowOpacity = 0.2
self.containerView.layer.cornerRadius = cornerRadius
self.containerView.layer.shadowColor = UIColor(named: "whiteColor")?.cgColor
}
And this is whiteColor
:
And now my problem is
When I change the appearance of the phone the
shadowsPath color
doesn't change automatically. What should I do to make the color dynamic?
回答1:
All layer properties don't react to color changes automatically (due to the conversion to CGColor
).
Instead, react to trait collection changes and re-set the properties when the color appearance changes:
override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if #available(iOS 13, *), self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
// re-set your properties here
}
}
回答2:
add
self.view.layoutIfNeeded()
in your function.It might solve your issue. In alternative way you will add color in viewDidLayoutSubviews
.
回答3:
So this is what worked for me - it's a mix between Frank Schlegel's answer and between Kurt Revis's answer to the cgColor question
override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if #available(iOS 13, *), self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
SubmissionOptionsMenu.layer.shadowColor =
UIColor.label.resolvedColor(with: self.traitCollection).cgColor
}
}
来源:https://stackoverflow.com/questions/58092716/uiviews-shadowpath-color-doesnt-change