-2

My designer send me a button image with shadow which is complicate, so I need to use the button image instead of implementing the shadow myself. For example, the clickable red area is 20*20 and the whole image with shadow is 60*60. The red area is not in the center of the image.

The question is I want to make a 20*20 button and it can show the whole image.

The implement I'm using is adding an UIImageView (size=60*60) into a button(size=20*20). Is there any other way to do it? I think there's a way to use only image and button without an additional UIImageView

enter image description here

remykits
  • 1,735
  • 4
  • 18
  • 20

1 Answers1

0

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.

jcdr04
  • 90
  • 1
  • 8