iOS开发两个距离较近的按钮同时触发事件的解决方法

最繁琐的一种方法是(给按钮加判断):

//  Created by Mini on 16/3/11.
//  Copyright © 2016年 IZHUO.NET. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong,readonly) UIButton *firstButton;
@property (nonatomic,strong,readonly) UIButton *secondButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //为第一个button添加事件
    _firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_firstButton addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [_firstButton addTarget:self action:@selector(recordButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_firstButton addTarget:self action:@selector(recoveryButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    //为第二个button添加事件
    _secondButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_secondButton addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [_secondButton addTarget:self action:@selector(recordButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_secondButton addTarget:self action:@selector(recoveryButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark -- 事件响应
//点击按钮到离开屏幕响应事件时恢复按钮的状态并触发事件
- (void)actionButton:(UIButton *)sender {
    _firstButton.enabled = YES;
    _secondButton.enabled = YES;
    if (sender == _firstButton) {
        [self firstButtonPressed];
    }
    else if (sender == _secondButton) {
        [self secondButtonPressed];
    }
}

// 当按钮点下时把另一按钮设置不可点
- (void)recordButtonAction:(UIButton *)sender {
    if (sender == _firstButton) {
        _secondButton.enabled = NO;
    }
    else if (sender == _secondButton) {
        _secondButton.enabled = NO;
    }
}
//当点下按钮从按钮区域外离开时恢复button状态
- (void)recoveryButtonAction:(UIButton *)sender {
    _firstButton.enabled = YES;
    _secondButton.enabled = YES;
}

- (void)firstButtonPressed {
    //第一个按钮事件处理
}
- (void)secondButtonPressed {
    //第二个按钮事件处理
}

最简单一种方法是:
[_firstButton setExclusiveTouch:YES];
[_secondButton setExclusiveTouch:YES];
这个是UIView的成员方法, 只要是继承自UIView的控件都可以用。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╰つ栺尖篴夢ゞ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值