您的位置:首页 > 移动开发 > IOS开发

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

2016-03-12 21:42 761 查看
最繁琐的一种方法是(给按钮加判断):

//  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的控件都可以用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息