iOS Development

ios – Add a picture to a subclass of UIVIew

Spread the love

It would not appear like you are ever establishing any auto format constraints for the UIImageView (or MyView for that matter). Due to this, my guess is that even when the background coloration of the UIView is displaying, the imageView’s body is 0 top and 0 width. It’s best to be capable to see this when utilizing the “Debug View Hierarchy” possibility inside Xcode whereas working your app.

Debug View Hierarchy

0 Size

Here is an instance adjusting your code to incorporate auto format constraints for the view and the imageView which ought to enable the picture to point out up correctly:

class MyViewController: UIViewController {
    let myView = MyView()

    override func viewDidLoad() {
        myView.translatesAutoresizingMaskIntoConstraints =  false
        myView.backgroundColor = .systemPink
        myView.widthAnchor.constraint(equalToConstant: 50).isActive = true
        myView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    @IBAction @objc func changeImageFunc(_ sender: Any) {
        // simply an instance picture
        let picture = UIImage(systemName: "eraser")!
import UIKit

class MyView: UIView {

    var imageView: UIImageView
    override init(body: CGRect) {
        imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        tremendous.init(body: body)
        imageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        imageView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
        imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been carried out")
    func setImage(_ picture: UIImage) {
         // Set the picture for the inner UIImageView
         imageView.picture = picture


Which leads to:

ImageView example

Leave a Reply

Your email address will not be published. Required fields are marked *