【问题标题】:Center ImageView Vertically with offset以偏移量垂直居中 ImageView
【发布时间】:2018-02-01 22:35:28
【问题描述】:

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

iPhone 8(下图是iPhone 8的界面生成器截图。)

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

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

如何让它适用于所有屏幕尺寸?

【问题讨论】:

标签: swift xcode autolayout interface-builder


【解决方案1】:

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

最终随着尺寸等级的变化:

我教你如何通过代码解决:

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 anchor,只使用centerX和centerY(负偏移)

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多