居中 ImageView 垂直偏移

Center ImageView Vertically with offset

我想将图像视图水平居中,然后垂直居中。但是,在垂直居中时,我需要图像视图稍微偏离中心,有利于视图的上半部分。我的设计师给了我 214 点的顶部间距,这在 iPhone 6,7,8 上非常完美。但是在 iPad 上它不能正确缩放。在具有 iPhone 4S 的频谱的另一端,图像视图有利于视图的下半部分。

iPhone 8(下图为iPhone 8设置的界面生成器截图。)

iPad(下图是为iPad Pro 9.7设置的界面生成器截图。)

iPhone 4S(下图为iPhone 4S设置的界面生成器截图。)

我怎样才能让它适应所有屏幕尺寸?

您可以通过应用故事板 (centerXAnchor, centerYAnchor-offset) 中的约束来解决它:

最终尺寸 class 变化:

我用代码告诉你如何解决:

import UIKit

class ViewController: UIViewController {
    let IMAGE_SIZE:CGFloat = 200 // whatever
    let OFFSET:CGFloat = -60 // whatever

    override func viewDidLoad() {
        super.viewDidLoad()

        let niceIcon = UIImageView(image: UIImage(named: "icon"))
        self.view.addSubview(niceIcon)

        niceIcon.translatesAutoresizingMaskIntoConstraints = false
        niceIcon.widthAnchor.constraint(equalToConstant: IMAGE_SIZE).isActive = true
        niceIcon.heightAnchor.constraint(equalToConstant: IMAGE_SIZE).isActive = true
        niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: self.view.centerXAnchor).isActive = true
        niceIcon.centerYAnchor.constraint(lessThanOrEqualTo: self.view.centerYAnchor, constant: OFFSET).isActive = true
    }
}

关键是:不要使用 top/left/right/bottom 锚点,只需使用 centerX 和 centerY(带负偏移量)