【问题标题】:How to remove extra black shadow in some iPhones while giving shadow for UIView in swift?如何在快速为 UIView 提供阴影的同时去除某些 iPhone 中的额外黑色阴影?
【发布时间】:2020-04-30 01:39:25
【问题描述】:

我为三个视图提供了阴影。阴影在 iPhone 8 plus、iPhone 11、iPhone 11 pro max 中完美呈现。如下所示

我在 iPhone 8、iPhone 7 plus、iPhone 7 的右侧出现深黑色阴影,为什么?如下所示

如何在 iPhone8 中去除右侧的黑色。

下面的 UIView 阴影代码:

firstContainerView.clipsToBounds = false
firstContainerView.layer.shadowColor = UIColor.black.cgColor
firstContainerView.layer.shadowOpacity = 1
firstContainerView.layer.shadowOffset = CGSize(width: 0.2, height: 0.2)
firstContainerView.layer.shadowRadius = 1
firstContainerView.layer.shadowPath = UIBezierPath(roundedRect: 
firstContainerView.bounds, cornerRadius: cornerRadius).cgPath

为什么某些设备会出现额外的黑色阴影。 请帮我去除 iPhone 8、iPhone 7 plus 阴影中多余的黑色。

【问题讨论】:

    标签: swift iphone uiview shadow


    【解决方案1】:

    根据this answer,您可以使用您的参数创建扩展:

    extension UIView {
        func addShadow() {
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0.2, height: 0.2)
            layer.shadowRadius = 1
            layer.shadowOpacity = 1
            layer.masksToBounds = false
    
            updateShadow()
        }
        func updateShadow() {
            layer.shadowPath = UIBezierPath(roundedRect: self.bounds,cornerRadius: 5).cgPath
        }
    }
    

    并像这里一样在viewDidLayoutSubviews() 中调用它

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        viewTest.addShadow()
    }
    

    我希望这对你的 iPhone 7 等有帮助。

    【讨论】:

    • 是的,它完美地工作,我可以知道我在上面的帖子中哪里出错了.. 为什么我用来获得额外的黑色?为什么我没有得到你的答案?
    • @iPhoneDev 我想说这与视图控制器的生命周期有关。您可以在viewDidLoad()viewDidLayoutSubviews 中查看viewTest.bounds,iPhone 7/8 的尺寸很可能不同,但 iPhone 8 Plus 的尺寸相同(为什么 - 老实说,我不知道),因为viewDidLayoutSubviews сalled通知视图控制器它的视图刚刚布置了它的子视图。因此,有必要根据视图控制器上view 大小的当前(最新)信息更新我们的shadowPath
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2016-11-14
    • 2020-10-05
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多