1

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?

Atarang
  • 422
  • 1
  • 6
  • 22

2 Answers2

0

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.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
  • @ Yes, if the trick you described works then I'll change inside buttons to labels. I'll try the suggestion and update the results. – Atarang Feb 25 '18 at 19:32
  • 1
    Actually that did not work exactly because of little complicated layout than what I described. In above scenario I'd multiple stack views because of design. I'd row of image,label,image in a vertical stack view and there was another row of views in another horizontal stack view and both of them were in a vertical stack view. Adding a button as suggested turned out little difficult. Your suggestion was useful but I solved it as follows, I removed two horizontal stack views and used 'UIVIEW to hold image,lable,button and then added two UIViEWs in to a vertical stackview. This worked. – Atarang Feb 28 '18 at 06:17
0

You can't add an item inside stackView with specific alignment than the others you should create that transparent button in same hierarchy with frame of it equal to stackView's frame or set it with autolayout Top, bottom,leading and trailing

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87