菜鸟教程小白 发表于 2022-12-13 09:46:55

objective-c - 在 iOS 中触发 Touch Down 的重复事件


                                            <p><p>我正在开发一个应用程序,我希望每隔几秒调用一次方法,同时用户将手指放在按钮上,并在释放时停止。</p>

<p>目前我正在触发 Touch Down 事件的 NSOperation,然后应该调用 NSTimer 以在 2 秒后触发另一个 NSOperation。</p>

<p>然而,只有第一个“runOperation”正在发生;计时器中的不是。</p>

<pre><code>- (IBAction)buttonPressed:(id)sender
{
    ;
}

- (void)runOperation {
    NSInvocationOperation *operation = [ initWithTarget:self
                                                                            selector:@selector(doStuff)
                                                                        object:nil];

    ;
    ;
}

- (void)doStuff {
    /* stuff goes here */

    ;
}

- (void)setTimer
{
    timer = [ retain];
}

- (IBAction)finishTakingPictures:(id)sender {
    ;
    timer = nil;
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>XJones(没有关系)关于计划的计时器和荒谬的间接数量是正确的。但我个人确实喜欢这种用户交互模型的 NSTimer。以下是我将如何实现它。</p>

<pre><code>_buttonTimer is an instance variable,
button is an IBOutlet to the button in question,
touchDown: is connected to the button&#39;s TouchDown event.
</code></pre>

<p>将按钮添加为 socket 无需使用 BOOL 来跟踪按钮状态,因为按钮知道它的状态。</p>

<p>然后将这些方法添加到您的 UIViewController 子类中。</p>

<pre><code>-(void)helloMe{
    if (self.button.state == UIControlStateNormal){
      ;
      _buttonTimer = nil
    }
    else {
      NSLog(@&#34;Hello me&#34;);
      // Do stuff here
    }
}

- (IBAction)touchDown:(id)sender {
    _buttonTimer = ;
    ; // If desired
}
</code></pre>

<p>现在运行,您将在按下按钮时在控制台中看到“Hello me”,每两秒一次,直到您松开按钮。</p></p>
                                   
                                                <p style="font-size: 20px;">关于objective-c - 在 iOS 中触发 Touch Down 的重复事件,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/8172386/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/8172386/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: objective-c - 在 iOS 中触发 Touch Down 的重复事件