首页 > 解决方案 > Swift:以编程方式自动布局图像

问题描述

在我的 Swift 应用程序中,我插入了这样的图像:

let ImageNavig = "5.jpg"
        let image1 = UIImage(named: ImageNavig)
        let image1View = UIImageView(image: image1!)
        let yCenter1 = self.view.center.y
        let Image1Size = CGPoint(x: 420, y: 240)
        image1View.frame = CGRect(x: 0, y: -10, width: Image1Size.x, height: Image1Size.y)
        view.addSubview(image1View)

但是,当我使用较旧的 Iphone 运行项目时,结果是这样的: 在此处输入图像描述

如何在没有情节提要的情况下以编程方式插入自动布局?

标签: swiftautolayoutconstraints

解决方案


如果您在旧 iphone 中遇到图像宽度问题,那是因为您已经为图像提供了固定宽度,使用下面的代码它将根据 iphone 宽度动态获取宽度

let Image1Size = CGPoint(x: self.view.frame.width, y: 240)

代替

let Image1Size = CGPoint(x: 420, y: 240)

推荐阅读