How can I bring a view in front of another view, i

2019-02-16 15:05发布

Below are how my views are organized in IB, top->bottom when the app is started.

The user can do something to make "Category Table View Header" temporarily expand over "Name View" - however once doing so, the .TouchDown action assigned to "Category Table View Header" no longer works wherever it overlaps with "Name View" (i.e., the user can tap the header anywhere it doesn't overlap with name view and it still works).

enter image description here

I know that may be confusing, so I drew out some boxes. On the left is the original, right is after user action - problem is on the right the action on the red box only works if the user taps the bottom half, not the top half.

enter image description here

My guess is its because the header is lower in the view hierarchy than the name view, but it would be hard for me to change that without messing around with a bunch of constraints.

I also tried setting nameView.hidden = true, but that doesn't work.

4条回答
仙女界的扛把子
2楼-- · 2019-02-16 15:28

You can take a control over the order of subviews using methods: bringSubviewToFront and sendSubviewToBack from the superview.

You can access all the subviews contained by superview using self.view.subview array.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-16 15:40

The method has been updated since swift 3

What has worked for me and hopefully for you is using :

YourView.bringSubview(toFront: yourelementA)
YourView.bringSubview(toFront: yourelementB)

Alternatively you could use the following to send the object that is in the front:

YourView.sendSubview(toBack: yourelementC)

I hope this helps

查看更多
虎瘦雄心在
4楼-- · 2019-02-16 15:42

In Swift 4.2

To bring a subview to front

self.view.bringSubviewToFront(yourView)

To send a subview to back

self.view.sendSubviewToBack(yourView)
查看更多
淡お忘
5楼-- · 2019-02-16 15:45

If you want to bring a subview to the front, you can use:

SWIFT 4 UPDATE

self.view.bringSubviewToFront(yourView)

SWIFT 3 UPDATE

self.view.bringSubview(toFront: yourView)

Send view to back:-

SWIFT 4 UPDATE

self.view.sendSubviewToBack(yourView)

SWIFT 3 UPDATE

self.view.sendSubview(toBack: yourView)
查看更多
登录 后发表回答