UIView 的 shadowpath 颜色没有改变

UIView's shadowpath color doesn't change

我有一个 UIView,我为它设置了一个 shadowPath,如下所示:

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
}

这是whiteColor:

现在我的问题是

When I change the appearance of the phone, the shadowPath's color doesn't change automatically. What should I do to make the color dynamic?

所有图层属性不会自动对颜色变化做出反应(由于转换为 CGColor)。

相反,对特征集合变化做出反应并在颜色外观变化时重新设置属性:

override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    if #available(iOS 13, *), self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
        // re-set your properties here
    }
}

添加 self.view.layoutIfNeeded() 在您的 function.It 中可能会解决您的问题。以替代方式,您将在 viewDidLayoutSubviews.

中添加颜色

所以这对我有用 - 它是 Frank Schlegel's answer and between Kurt Revis's

之间的混合
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
   }
}