【问题标题】:Constraints affecting shadow of UIView?影响 UIView 阴影的约束?
【发布时间】:2019-01-09 18:21:17
【问题描述】:

我试图在我的 ViewController 中的 UIView 的所有四个侧面上建立一个阴影——在我通过 Xcode 向 UIView 添加约束之前,它工作得非常好。如何使 UIView 的阴影在所有四个面上显示并为所有面设置约束?

基本上,我发现每当我通过 Xcode 将约束应用到我设置了阴影的 UIView 时,阴影不会出现在 UIView 的所有四个侧面下。相反,它向左浮动,使右侧和底部完全没有阴影。这可以在下面的屏幕截图中看到。

https://imgur.com/a/bZgYPH8

class RegistrationViewController: UIViewController {
    @IBOutlet weak var signUpView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        signUpView.clipsToBounds = true
        signUpView.layer.cornerRadius = 20;
        signUpView.layer.shadowPath = UIBezierPath(roundedRect: signUpView.bounds, cornerRadius: signUpView.layer.cornerRadius).cgPath
        signUpView.layer.shouldRasterize = true
        signUpView.layer.shadowColor = UIColor.black.cgColor
        signUpView.layer.shadowOffset = .zero
        signUpView.layer.shadowOpacity = 1
        signUpView.layer.shadowRadius = 20
        signUpView.layer.masksToBounds = false

    // Do any additional setup after loading the view.
    }
}

为什么会发生这种情况?如何在保持预期结果的同时添加约束?

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    在 viewDidLoad 中,您的约束尚未生效。因此,当您创建 UIBezierPath 时,边界不会更新为自动布局约束。使用的边界可能是您的 .xib 文件中的边界。

    将你的 shadowMakingPath 移动到 viewDidLayoutSubviews

    override func viewDidLayoutSubviews() {
       super.viewDidLayoutSubivews()
       signUpView.layer.shadowPath = UIBezierPath(roundedRect: signUpView.bounds, cornerRadius: signUpView.layer.cornerRadius).cgPath
       signUpView.layer.shouldRasterize = true
       signUpView.layer.shadowColor = UIColor.black.cgColor
       signUpView.layer.shadowOffset = .zero
       signUpView.layer.shadowOpacity = 1
       signUpView.layer.shadowRadius = 20
       signUpView.layer.masksToBounds = false
    }
    

    更多信息..Objective-C/Swift (iOS) When are the auto-constraints applied in the View/ViewController work flow?

    【讨论】:

    • 我试过了,但我得到的结果还是一样。我在相关文件中创建了一个 viewWillLayoutSubviews 函数,有什么想法我可能做错了吗?我应该以某种方式更新 .xib 文件吗?抱歉,我对 Swift 编码很陌生。
    • 如果您的约束有效,您不需要更新 xib。尝试使用框架而不是使用边界?查看更新的答案。
    • 我这样做了,现在阴影漂浮在右侧而不是左侧。虽然结果相同。你指的是我的.xib 的.storyboard 文件吗?否则,我没有设置 .xib 文件。
    • 是的,.xib 通常是 .storyboard 文件中的一个单独的屏幕(您不必担心这个问题)。你能给我们截图你的 UIView 约束以及它在你的故事板中的样子吗?
    • 我不确定是什么问题。您是否覆盖了 func 并调用了 super ?如果你在 viewdidLoad 和 viewWillLayoutSubviews 中放了一个断点,你能在这两个函数中都放 signUpView.frame 吗?
    猜你喜欢
    • 2014-08-16
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多