Попробуйте что-то вроде этого, чтобы центрировать его внутри вида.
Важные строки кода для центрирования UIImageView
выглядят следующим образом:
overlayImageView.translatesAutoresizingMaskIntoConstraints = false
overlayImageView.contentMode = .center
qrCodeImageView.addSubview(overlayImageView)
let centerXConst = NSLayoutConstraint(item: overlayImageView, attribute: .centerX, relatedBy: .equal, toItem: qrCodeImageView, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConst = NSLayoutConstraint(item: overlayImageView, attribute: .centerY, relatedBy: .equal, toItem: qrCodeImageView, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerXConst, centerYConst])
Я использую этот точный код для центрирования значка в QR-коде:
class ViewController: UIViewController {
@IBOutlet weak var qrCodeImageView: UIImageView!
var qrCodeImage: CIImage!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let textField = "fooqarcode"
let data = textField.data(using: String.Encoding.isoLatin1, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
qrCodeImage = (filter?.outputImage)!
let scaleX = qrCodeImageView.frame.size.width / qrCodeImage.extent.size.width
let scaleY = qrCodeImageView.frame.size.height / qrCodeImage.extent.size.height
let transformedImage = qrCodeImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))
qrCodeImageView.image = UIImage(ciImage: transformedImage)
let overlayImageView = UIImageView(image: UIImage(named: "block.png"))
overlayImageView.translatesAutoresizingMaskIntoConstraints = false
overlayImageView.contentMode = .center
qrCodeImageView.addSubview(overlayImageView)
let centerXConst = NSLayoutConstraint(item: overlayImageView, attribute: .centerX, relatedBy: .equal, toItem: qrCodeImageView, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConst = NSLayoutConstraint(item: overlayImageView, attribute: .centerY, relatedBy: .equal, toItem: qrCodeImageView, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerXConst, centerYConst])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}