Search code examples
iosswiftstackview

covering stackview with a transparent button


I've a horizontal stackview with 3-subviews (a image view, a button and another button with an image) as shown below,

view
  stackview
     imageview
     button
     button
or
image|button|button

I would like to add a transparent button to this stackview covering all three views so that I can assign a single action when user clicks on it. But I don't know how to do this? Is there a trick to achieve this?


Solution

  • Add it directly to the view after you added a stackView (so it will be rendered after the stackView):

    view
       stackView
          imageview
          button
          button
       transparentButton
    

    The trick here is, that if the view.addSubview(stackView) is followed by view.addSubview(transparentButton), then transparentButton is rendered above the stackView and its content, and it will get the touch events instead of the content behind.

    And then just add constraints that will make it copy the stackView frame:

    NSLayoutConstraint.activate([
        transparentButton.leftAnchor.constraint(equalTo: stackView.leftAnchor),
        transparentButton.rightAnchor.constraint(equalTo: stackView.rightAnchor),
        transparentButton.topAnchor.constraint(equalTo: stackView.topAnchor),
        transparentButton.bottomAnchor.constraint(equalTo: stackView.bottomAnchor),
    ])
    

    Although I must say that it seems a bit weird that you want to add a button to overlay other buttons. Maybe you want to replace those buttons in stackView with UILabels.