详解iOS中Button按钮的状态和点击事件

2020-01-18 14:09:42王冬梅

一、按钮的状态

1.UIControlStateNormal

    1> 除开UIControlStateHighlightedUIControlStateDisabledUIControlStateSelected以外的其他情况,都是normal状态

    2> 这种状态下的按钮【可以】接收点击事件

2.UIControlStateHighlighted

    1> 【当按住按钮不松开】或者【highlighted = YES】时就能达到这种状态

    2> 这种状态下的按钮【可以】接收点击事件

3.UIControlStateDisabled

    1> 【button.enabled = NO】时就能达到这种状态

    2> 这种状态下的按钮【无法】接收点击事件

4.UIControlStateSelected

    1> 【button.selected = YES】时就能达到这种状态

    2> 这种状态下的按钮【可以】接收点击事件

二、让按钮无法点击的2种方法

     1> button.enabled = NO;

     *【会】进入UIControlStateDisabled状态

     2> button.userInteractionEnabled = NO;

     *【不会】进入UIControlStateDisabled状态,继续保持当前状态

三、iOS中按钮点击事件处理方式

在iOS开发中,时常会用到按钮,通过按钮的点击来完成界面的跳转等功能。按钮事件的实现方式有多种,其中

较为常用的是目标-动作对模式。但这种方式使得view与controller之间的耦合程度较高,不推荐使用;

另一种方式是代理方式,按钮的事件在view中绑定,controller作为view的代理实现代理方法。

目标-动作对实现方式

具体来说,假设我们有一个包含一个Button的veiw,view将Button放在头文件中,以便外部访问。然后controller将view作为自己的view,在viewcontroller中实现按钮的点击事件。

文字描述起来好像不够直观,直接上代码

1、MyView.h

包含一个可被外部访问的按钮的view


@interface MyView : UIView

@property (strong, nonatomic) UIButton *myBtn;

@end

2、MyView.m


#import "MyView.h" 

@implementation MyView
//view的初始化方法
- (id)initWithFrame:(CGRect)frame
{
 self = [super initWithFrame:frame];
 if (self)
 { //初始化按钮
 _myBtn = [[UIButton alloc] initWithFrame:CGRectMake(140, 100, 100, 50)];
 _myBtn.backgroundColor = [UIColor redColor];
 //将按钮添加到自身
 [self addSubview:_myBtn];
 }
 return self;
}

@end

3、MyViewController.h


#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController

@end

4、MyViewController.m