我下面的这段代码将图像放置在视图上。问题是从iPhone转移到iPad时,创建固定的高度和宽度不起作用。我希望代码转移整个画布,而不是固定的数量。
@IBOutlet weak var jj: draw!
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "se")
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 300)
jj.addSubview(imageView)
}
最佳答案
您可以轻松地使用自动布局完成此任务。
let backgroundImage : UIImageView = {
let image = UIImageView(image: #imageLiteral(resourceName: "name-of-image"))
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = .scaleToFill
return image
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
}
func setUpView(){
view.addSubview(backgroundImage)
NSLayoutConstraint.activate([
backgroundImage.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
backgroundImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
backgroundImage.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
backgroundImage.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
}