88

ボタンの長押しをエミュレートしたいのですが、どうすればよいですか? タイマーは必要だと思います。わかりUILongPressGestureRecognizerましたが、このタイプをどのように利用できますか?

4

9 に答える 9

161

UILongPressGestureRecognizerインスタンスを作成してボタンにアタッチすることから始めることができます。

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[longPress release];

そして、ジェスチャーを処理するメソッドを実装します

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
         NSLog(@"Long Press");
    }
}

これが基本的なアプローチになります。プレスの最小時間と許容できるエラーの量を設定することもできます。また、ジェスチャを認識した後にメソッドが数回呼び出されるため、最後に何かを実行する場合は、その状態を確認して処理する必要があることに注意してください。

于 2011-05-30T18:27:38.813 に答える
28

受け入れられた回答の代わりに、Interface Builder を使用して Xcode でこれを非常に簡単に行うことができます。

長押しジェスチャ レコグナイザオブジェクト ライブラリからドラッグし、長押しアクションを実行するボタンの上にドロップするだけです。

次に、先ほど追加したLong Press Gesture Recognizerの Action をView Controller に接続し、送信者のタイプを に選択しますUILongPressGestureRecognizer。これをIBAction使用するコードでは、受け入れられた回答で提案されているコードと非常によく似ています。

Objective -C の場合:

if ( sender.state == UIGestureRecognizerStateEnded ) {
     // Do your stuff here
}

またはスウィフトで:

if sender.state == .Ended {
    // Do your stuff here
}

しかし、私はそれを試した後、@shengbinmeng が受け入れられた回答へのコメントとして行った提案を好むことを認めなければなりません。

Objective -C の場合:

if ( sender.state == UIGestureRecognizerStateBegan ) {
     // Do your stuff here
}

またはスウィフトで:

if sender.state == .Began {
    // Do your stuff here
}

違いは、Endedでは、指を離したときに長押しの効果が表示されることです。ではBegan、画面から指を離す前であっても、長押しがシステムにキャッチされるとすぐに、長押しの効果が表示されます。

于 2014-11-05T12:18:03.647 に答える
19

受け入れられた回答の迅速なバージョン

おそらくほとんどのユーザーが自然に期待するものなので、UIGestureRecognizerState.Beganではなくを使用するという追加の変更を加えました。.Endedただし、両方を試してみて、自分の目で確かめてください。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add gesture recognizer
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        self.button.addGestureRecognizer(longPress)
        
    }

    func longPress(gesture: UILongPressGestureRecognizer) {
        if gesture.state == UIGestureRecognizerState.began {
            print("Long Press")
        }
    }
    
    @IBAction func normalButtonTap(sender: UIButton) {
        print("Button tapped")
    }
}
于 2015-12-04T07:41:47.123 に答える
10

これを試して:

viewDidLoad:以下のようにボタンを追加する

-(void)viewDidLoad {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTag:1]; //you can set any integer value as tag number
    btn.title = @"Press Me";
    [btn setFrame:CGRectMake(50.0, 50.0, 60.0, 60.0)];

    // now create a long press gesture
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressTap:)];
    [btn addGestureRecognizer:longPress];
}

このようにジェスチャメソッドを呼び出します

-(void)longPressTap:(id)sender {
     UIGestureRecognizer *recognizer = (UIGestureRecognizer*) sender
    // Recogniser have all property of button on which you have clicked
    // Now you can compare button's tag with recogniser's view.tag  
    // View frame for getting the info on which button the click event happened 
    // Then compare tag like this
    if(recognizer.view.tag == 1) { 
       // Put your button's click code here
    }

    // And you can also compare the frame of your button with recogniser's view
    CGRect btnRect = CGRectMake(50.0, 50.0, 60.0, 60.0);
    if(recogniser.view.frame == btnRect) {
       //put your button's click code here
    }

   // Remember frame comparing is alternative method you don't need  to write frame comparing code if you are matching the tag number of button 
}
于 2012-05-18T14:59:24.313 に答える
4

あなたには私の解決策が必要だと思います。

シングルプレス用にこのコードが必要です

- (IBAction)buttonDidPress:(id)sender {
    NSLog("buttonDidPress");
}

まず、長押しジェスチャーをボタンに追加します

- (void)viewWillAppear:(BOOL)animated
{
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonDidLongPress:)];
    [self.button addGestureRecognizer:longPress];
}

長押しジェスチャが認識された場合は、シングルプレスイベントを繰り返し呼び出します。

- (void)buttonDidLongPress:(UILongPressGestureRecognizer*)gesture
{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(buttonDidPress:) userInfo:nil repeats:YES];

            NSRunLoop * theRunLoop = [NSRunLoop currentRunLoop];
            [theRunLoop addTimer:self.timer forMode:NSDefaultRunLoopMode];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [self.timer invalidate];
            self.timer = nil;
        }
            break;
        default:
            break;
    }
}
于 2015-05-24T08:22:26.440 に答える
0

アプリ用にサブクラス化された UIButton があるので、実装を取り出しました。これをサブクラスに追加するか、UIButton カテゴリと同じくらい簡単に再コーディングできます。

私の目標は、すべてのコードでビュー コントローラーを乱雑にすることなく、ボタンに長押しを追加することでした。ジェスチャ レコグナイザーの状態が開始されたときにアクションを呼び出す必要があると判断しました。

わざわざ解決したことがないという警告が出てきます。リークの可能性があると言っていますが、コードをテストしてリークしていないと思います。

@interface MYLongButton ()
@property (nonatomic, strong) UILongPressGestureRecognizer *gestureRecognizer;
@property (nonatomic, strong) id gestureRecognizerTarget;
@property (nonatomic, assign) SEL gestureRecognizerSelector;
@end

@implementation MYLongButton

- (void)addLongPressTarget:(CGFloat)interval target:(id)target action:(SEL)selector
{
    _gestureRecognizerTarget = target;
    _gestureRecognizerSelector = selector;
    _gestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressGestureRecognizer:)];
    _gestureRecognizer.minimumPressDuration = interval;

    [self addGestureRecognizer:_gestureRecognizer];
}

- (void)handleLongPressGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSAssert([_gestureRecognizerTarget respondsToSelector:_gestureRecognizerSelector], @"target does not respond to selector");

        self.highlighted = NO;

        // warning on possible leak -- can anybody fix it?
        [_gestureRecognizerTarget performSelector:_gestureRecognizerSelector withObject:self];
    }
}

アクションを割り当てるには、この行を viewDidLoad メソッドに追加します。

[_myLongButton addLongPressTarget:0.75 target:self selector:@selector(longPressAction:)];

アクションは、すべての IBAction と同様に (IBAction なしで) 定義する必要があります。

- (void)longPressAction:(id)sender {
    // sender is the button
}
于 2015-09-22T13:53:02.650 に答える