swift - 有没有办法根据 SWIFT 中的屏幕尺寸自动调整图像或任何内容的大小?
问题描述
我一直在尝试找到一种方法来以编程方式根据屏幕尺寸调整图像大小而不使用情节提要?
解决方案
转到谷歌(或您最喜欢的搜索引擎)并搜索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 上,横向:
推荐阅读
- swift - 快速加载图像需要更多时间
- swift - 无法导航到 UITabBarController
- oracle - Creationg 触发器以限制新地址记录的 NULL 值
- c++ - 阅读自动生成的 DOLFIN c++ 库文档
- c - 在c中对正浮点数进行排序
- android - 调用 REST API 的协程 -> FATAL EXCEPTION : main
- django - 如何在 Django 中将二维码图像保存为模型字段
- java - 有没有办法在 JList 中使用枚举?
- azure-resource-manager - 通过 ResourceManagementClient 触发模板部署时设置参数
- javascript - 引导模式未正确执行