【问题标题】:How can I make an animated view be a consistent distance from the bottom of the screen on all devices?如何使动画视图在所有设备上与屏幕底部的距离保持一致?
【发布时间】:2020-03-25 10:34:47
【问题描述】:

我正在开发一项功能,该功能将在屏幕底部为UIView 设置动画,以告诉用户他们的数据已保存。但是,它在 iPhone 11 Pro Max 上的出现位置与在 iPhone X 上不同。

iPhone 11 Pro Max(这是我想要的样子):

但在 iPhone X 上:

我可能应该注意到我在情节提要上创建了视图,并有一个@IBOutlet 连接到它。在故事板上,它位于您在顶部屏幕截图中看到的位置。我没有对其施加任何限制。其余的在代码中完成。

动画的代码很简单:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    savedView.center.y += view.bounds.height // start with it off the screen 
    savedView.center.x = (view.bounds.width / 2)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    // animate it onto the screen
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: [], animations: {
        self.savedView.center.y -= self.view.bounds.height <-- the problem must be here

    }, completion: nil)

}

我认为这可能是由于设备尺寸等级不同,但所有 iPhone 都是“常规”高度,所以我不认为是这样。

如何让这个视图在所有设备上都位于相同的位置(相对于屏幕底部)?

【问题讨论】:

    标签: ios swift uiview uiviewanimation


    【解决方案1】:

    为了将您的视图放置在所有设备上的相同位置,必须设置约束。这样,系统才能正确显示您的视图。

    因此,要为您的视图实现底部居中的附加行为,您需要为 safe-area bottom 设置一个约束,该约束称为 centered-horizo​​ntally , widthheight,假设这个视图是屏幕上的唯一组件。如果不是,那么组件在其顶部的视图必须有一个顶部约束

    希望这会有所帮助,至少能给你一个想法。

    Constraints reference

    【讨论】:

    • 但是我正在将视图从屏幕外的位置动画到最终位置,如您在第一个屏幕截图中看到的那样。我不认为添加这些约束会起作用
    • 哦,好的。我误解了你的问题。无论如何,您应该始终对现实世界的应用程序使用约束。您找到的解决方案实际上可以通过约束来完成。所以你不必担心 .center 和 bounds 的计算。
    【解决方案2】:

    我想通了。

    问题在于视图的初始center.y 位置从814 开始基于它在情节提要中的位置。因此,在我将其视为 iPhone 11 Pro 的情节提要上看起来不错,但是当在具有不同尺寸的其他设备模拟器上运行时,数学不再起作用。

    解决方案是根据view.bounds.height 设置center.y 位置,使其在任何设备上都具有一致的起始位置:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        savedView.center.y = (view.bounds.height - 60) // position the view 60 pixels bottom
        savedView.center.x = (view.bounds.width / 2) // center it horizontally
        savedView.center.y += view.bounds.height // move it outside the visible bounds
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多