0

如题,想点击屏幕,屏幕会有点暗半透明,手指离开屏幕,屏幕又恢复正常,和UIButton差不多。

在这种情况下,我知道UIButton要容易得多,但这只是一个示例

我的代码如下:

- (IBAction)tapped:(UITapGestureRecognizer *)sender
{
    UIView * tintView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:tintView];

    switch (sender.state) {
        case UIGestureRecognizerStateRecognized: {
        [tintView setBackgroundColor:[UIColor colorWithRed:.25 green:.25 blue:.25 alpha:.5]];
        NSLog(@"begin");
    }
    default: {
        [tintView setBackgroundColor:[UIColor clearColor]];
        NSLog(@"ended");
    }
    }
}

但是,当点击屏幕时,它不会像上面的代码那样改变,尽管begin并且ended被捕获在控制台中。

case如果在和default喜欢之间交换这些代码

    switch (sender.state) {
        case UIGestureRecognizerStateRecognized: {
        [tintView setBackgroundColor:[UIColor clearColor]];
        NSLog(@"begin");
    }
    default: {
        [tintView setBackgroundColor:[UIColor colorWithRed:.25 green:.25 blue:.25 alpha:.5]];
        NSLog(@"ended");
    }
    }

begin并且ended可以在控制台中显示,但是点击时屏幕会越来越暗,永远不会恢复正常,清晰的颜色。

我的代码有什么问题?如何让它发生?

谢谢!

4

2 回答 2

1

[self performSelector: withObject: afterDelay:] 将是完成此类事情的常用方法。

您将设置您的方法,分别关闭暗视图,然后将其作为选择器引用

[self performSelector:@selector(methodWhichDismissesDarkView:) withObject:nil afterDelay:0.2]

在视图变暗后立即调用它,0.2 秒后它会触发。

但是,要真正做到正确,请确保您可以使用以下方法优雅地处理延迟期间发生的中断:

[NSObject cancelPreviousPerformRequestsWithTarget:self];

当应用程序不再需要处理它时,它将取消挂起的操作。

于 2013-10-22T14:12:19.980 回答
0

按照@ryancumley 的提示,下面是更新的代码。

@property (strong, nonatomic)  UIView * tintView;
@synthesize tintView;

- (IBAction)tapped:(UITapGestureRecognizer *)sender
{
        switch (sender.state) {
        case UIGestureRecognizerStateRecognized: {
            [self.tintView setBackgroundColor:[UIColor colorWithWhite:0.000 alpha:0.150]];
            [self performSelector:@selector(setTintView:) withObject:nil afterDelay:.25];
            NSLog(@"begin");
        }
        default: {
            break;
            NSLog(@"ended");
        }
    }
}

- (void)setTintView:(UIView *)tintView
{
    [self.tintView setBackgroundColor:[UIColor colorWithRed:.25 green:.25 blue:.25 alpha:0]];
}

它终于可以工作了,看起来就像点击一个按钮。但是,NSLog(@"ended")没有触发。

为什么我的原版不能用?

这是更新的正确方法或解决方法吗?

于 2013-10-22T14:48:02.083 回答