首页 > 解决方案 > 有没有办法根据 SWIFT 中的屏幕尺寸自动调整图像或任何内容的大小?

问题描述

我一直在尝试找到一种方法来以编程方式根据屏幕尺寸调整图像大小而不使用情节提要?

标签: swiftautolayout

解决方案


转到谷歌(或您最喜欢的搜索引擎)并搜索swift add constraints programmatically. 这是非常非常基本的。

这是一个简单的例子:

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // create image view
        let imgView = UIImageView()
        
        imgView.backgroundColor = .systemYellow
        
        // create image
        let img = UIImage(systemName: "person.fill")
        imgView.image = img
        
        // add imageView to view
        view.addSubview(imgView)
        
        // use auto-layout
        imgView.translatesAutoresizingMaskIntoConstraints = false
        
        // respect safe area
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            // constrain imageView width to view safe-area width
            imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            // aquare image view (1:1 ratio)
            imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
            // center vertically
            imgView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
        ])
        
    }
}

结果:

在此处输入图像描述


编辑- 第二个例子......前三分之一,水平居中:

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(true, animated: false)
        // create image view
        let imgView = UIImageView()
        
        imgView.backgroundColor = .systemYellow
        
        // create image
        let img = UIImage(systemName: "person.fill")
        imgView.image = img
        
        // add imageView to view
        view.addSubview(imgView)
        
        // use auto-layout
        imgView.translatesAutoresizingMaskIntoConstraints = false
        
        // respect safe area
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            
            // you want the image view at the top?
            imgView.topAnchor.constraint(equalTo: g.topAnchor),
            
            // one-third of the height of the view?
            imgView.heightAnchor.constraint(equalTo: g.heightAnchor, multiplier: 1.0 / 3.0),
            
            // you want a aquare image view (1:1 ratio)?
            imgView.widthAnchor.constraint(equalTo: imgView.heightAnchor),
            
            // you want it centered horizontally?
            imgView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            
        ])
        
    }
}

在 iPhone 8 上:

在此处输入图像描述

在 iPhone 12 上:

在此处输入图像描述

在 9.7 英寸 iPad Pro 上,横向:

在此处输入图像描述


推荐阅读