Here's a simple example:
func createView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
// creating the container view
let view = UIView()
view.frame = CGRect(x: x, y: y, width: width, height: height)
view.backgroundColor = .systemRed
// creating the image view, set the image to the one you want
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
let image = UIImage(named: "myImage")
imageView.image = image
// creating the button
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: width / 3, height: height / 3)
button.backgroundColor = .systemBlue
// adding a tap response functionality to the button
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
// adding the button and image view to the container
view.addSubview(imageView)
view.addSubview(button)
//adding the container to the superview
self.view.addSubview(view)
}
Adding the method to handle a button tap:
@objc func buttonTapped() {
// all the code for handling a tap goes here
print("button tapped")
}
And finally calling createView()
in viewDidLoad()
:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createView(x: 100, y: 100, width: 60, height: 60)
}
It is important to note that the x and y values of the button and image do not refer to that of the superview, but rather to that of the container view.
If you want to add the shadow image, it must be include in the Assets.xcassets folder. From there, you can simply change the name to that of the image and it will be uploaded.