0

I've read this thread about custom window in iOS. Here it is, I create a new window and show it via window.hidden = NO; above the key window, the final goal is to make the custom window transparent and the btnAction within it could receive events.

If I set the window's userInteractionEnabled to NO, all the events sending to subviews of it will go through to the next lower level window (it's the key window here). If I disable the userInteractionEnabled line and leave it to YES defaultly, the custom window will suppress all the events with do nothing in the transparent area, but the btnAction will receive my expected event.

I know there is a way to let the custom window bypass the events from specified transparent area, just inherit the UIWindow to create a new subclass window and override these methods to achieve it.

// From UIView.h
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;   // recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;   // default returns YES if point is in bounds

I just wonder that are there any other quick easy ways to fix that without inheriting?

    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    window.windowLevel = UIWindowLevelNormal + 1;
    window.userInteractionEnabled = NO; // This will block the events which send to `btnAction`, too.
    // window.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.4];
    window.backgroundColor = UIColor.clearColor;

    UIButton *btnAction = [UIButton new];
    [btnAction setBackgroundImage:UIImageFromColor(RandomColor) forState:UIControlStateNormal];
    [btnAction addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:btnAction];

    [btnAction mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@60);
        make.right.equalTo(window).offset(-20);
        make.bottom.equalTo(window).offset(-60);
    }];
Itachi
  • 5,777
  • 2
  • 37
  • 69
  • I suppose you could swizzle those methods. See [this NSHipster article](https://nshipster.com/method-swizzling/). Maybe someone wants to post an example of how to swizzle this as an answer. – Smartcat Oct 30 '18 at 04:59
  • Swizzling the classes from the system framework will cause unexpected behaviors, I don't think that is a good idea. @Smartcat – Itachi Oct 30 '18 at 05:41
  • Heh, you asked for quick and easy, but didn't include "safe". :P But yes, you're correct. Just giving you an alternative. – Smartcat Oct 30 '18 at 05:43
  • Also, I suspect a swizzle expert could do it safely - but the rest of us should avoid it in production code. – Smartcat Oct 30 '18 at 05:53

0 Answers0