0

ボタンが押されている間もIBActionまたは関数を実行し続け、ボタンが離されるまで関数を継続して実行するようにボタン(IBActionおよびUIButtonが接続されている)を設定するにはどうすればよいですか。

値が変更されたレシーバーを接続する必要がありますか?

簡単な質問ですが、答えが見つかりません。

4

3 に答える 3

3
[myButton addTarget:self action:@selector(buttonIsDown) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonWasReleased) forControlEvents:UIControlEventTouchUpInside];


- (void)buttonIsDown
{
     //myTimer should be declared in your header file so it can be used in both of these actions.
     NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(myRepeatingAction) userInfo:nil repeats:YES];
}

- (void)buttonWasReleased
{
     [myTimer invalidate];
     myTimer = nil;
}
于 2012-08-17T00:59:45.070 に答える
2

ディスパッチソースiVarをコントローラーに追加します...

dispatch_source_t     _timer;

次に、touchDownアクションで、非常に多くの秒ごとに起動するタイマーを作成します。そこで繰り返し作業を行います。

すべての作業がUIで行われる場合は、キューを次のように設定します

dispatch_queue_t queue = dispatch_get_main_queue();

その後、タイマーはメインスレッドで実行されます。

- (IBAction)touchDown:(id)sender {
    if (!_timer) {
        dispatch_queue_t queue = dispatch_get_global_queue(
            DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        // This is the number of seconds between each firing of the timer
        float timeoutInSeconds = 0.25;
        dispatch_source_set_timer(
            _timer,
            dispatch_time(DISPATCH_TIME_NOW, timeoutInSeconds * NSEC_PER_SEC),
            timeoutInSeconds * NSEC_PER_SEC,
            0.10 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(_timer, ^{
            // ***** LOOK HERE *****
            // This block will execute every time the timer fires.
            // Do any non-UI related work here so as not to block the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                // Do UI work on main thread
                NSLog(@"Look, Mom, I'm doing some work");
            });
        });
    }

    dispatch_resume(_timer);
}

さて、タッチアップインサイドとタッチアップアウトサイドの両方に登録してください

- (IBAction)touchUp:(id)sender {
    if (_timer) {
        dispatch_suspend(_timer);
    }
}

必ずタイマーを破棄してください

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
        dispatch_release(_timer);
        _timer = NULL;
    }
}
于 2012-08-17T01:50:03.830 に答える
0

UIButtonは、touchDownイベントを使用して開始メソッドを呼び出し、touchUpInsideイベントを使用して終了メソッドを呼び出す必要があります

于 2012-08-17T00:42:29.297 に答える