UIView always top subview [duplicate]

2019-07-09 12:49发布

问题:

This question already has an answer here:

  • How to make a UIView always appear at the front? 4 answers

Hi I have a game where I create a subview that handles touch events. But when I add other objects later in the code, they appear in front of that view. So if the user tap the screen on one of these objects the touch won't be registered. So is there a way to make a UIView always appear on the top? I have tried this, but it doesn't work: view.layer.zPosition = MAXFLOAT;

Any ideas? Thanks

回答1:

Try with bringSubviewToFront:, did the trick for me:

[[self view] bringSubviewToFront:yourView];


回答2:

[[self view] bringSubviewToFront:yourView];


回答3:

If for some reason you don't want to keep a pointer to the subview as others have suggested you can add subviews using this method:

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index

with index = 0. This will insert each new subview under the previous. I would personally probably still do what @Alexander is doing in his answer/comments.