【Objective-C ・Swift】連続、高速、ボタン連打を禁止・無効化する


こんにちは、カミ@god48_です。
IOSでのデバック時にダブルタップや複数タップすることありますよね?
もちろん通常通りのアプリ動作であればそのようなことをすることはありませんが、デバック向けのダブルタップ、複数タップ無効をされる方法です。

ゲームの世界ではボタン連打はよくありますが、その他のアプリは必要ないですよね
それでは、実装していきましょう。
Objective-CでUserInteractionEnabledを実装

「UserInteractionEnabled
」はUIViewが持っているプロパティで、UIButtonやUIImageViewは「BOOL」判定することで「タップの有効無効」を切り替えできます。
「UserInteractionEnabled
」が「YES」になっていないと、タップしても実行されません。
もちろん何も指定しなければ、ボタンは押せるところか、連打もできます。

例えば、ダイアログの表示であれば、それが何度も呼ばれてしまします。
タップ無効(ダブルタップ無効)UserInteractionEnabled = NO;
// タップ無効
変数名.UserInteractionEnabled = NO;
BOOL判定で「NO」にすることでボタンが押せなくなります。
スポンサードサーチ
タップ有効(ダブルタップ有効)serInteractionEnabled = YES;
// タップ有効
変数名.UserInteractionEnabled = YES;
BOOL判定で「YES」にすることでボタンが押せるようになります。
画像のダブルタップ無効の方法
// UIImageを生成
UIImage *imageTitle = [UIImage imageNamed:@"画像"];
UIImageView *image = [[UIImageView alloc] initWithImage:imageTitle];
image.UserInteractionEnabled = NO;
画像のボタンを無効にする場合は「UIImage」を「UserInteractionEnabled = NO」にするだけです。
スポンサードサーチ
画像のダブルタップ有効の方法
// UIImageを生成
UIImage *imageTitle = [UIImage imageNamed:@"画像"];
UIImageView *image = [[UIImageView alloc] initWithImage:imageTitle];
image.UserInteractionEnabled = YES;
画像のボタンを無効にする場合は「UIImage」を「UserInteractionEnabled = YES」にするだけです。
// UIButtonの生成
UIButton *button = [[UIButton alloc]init];
ボタンのダブルタップ無効の方法
//タイトル・テキスト色・画像 通常
[button setTitle:@"ボタン" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.UserInteractionEnabled = NO;

最初に覚えたコードに生成や名前が付けただけですね
スポンサードサーチ
ボタンのダブルタップ有効の方法
// UIButtonの生成
UIButton *button = [[UIButton alloc]init];
//タイトル・テキスト色・画像 通常
[button setTitle:@"ボタン" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.UserInteractionEnabled = YES;

変数名を指定して、BOOL判定をすると切り替えができます。
ここまで学習できたということはSwift言語になっても大丈夫ですよね?
Swiftの例も合わせて覚えましょう。
SwiftでisUserInteractionEnabledを実装
Swiftでは「UserInteractionEnabled」ではなく「isUserInteractionEnabled」です。
似ていますが間違えないようにしましょう。
ボタンのダブルタップ無効の方法
//タップ有効
isUserInteractionEnabled = false
ボタンのダブルタップ有効の方法
// タップ無効
isUserInteractionEnabled = true
「isUserInteractionEnabled」をボタンアクションやif文をトリガーに「有効無効」を切り替えていきましょう。