详解iOS中Button按钮的状态和点击事件
详解iOS中Button按钮的状态和点击事件
发布时间:2016-12-28 来源:查字典编辑
摘要:一、按钮的状态1.UIControlStateNormal1>除开UIControlStateHighlighted、UIControlSt...

一、按钮的状态

1.UIControlStateNormal

1> 除开UIControlStateHighlighted、UIControlStateDisabled、UIControlStateSelected以外的其他情况,都是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

添加MyView作为自身view

#import "MyViewController.h" #import "MyView.h" @interface MyViewController () @property (strong, nonatomic) MyView *myview; @end @implementation MyViewController - (void)loadView { MyView *myView = [[MyView alloc] initWithFrame: [[UIScreen mainScreen] bounds] ]; self.view = myView; self.myview = myView; //在controller中设置按钮的目标-动作,其中目标是self,也就是控制器自身,动作是用目标提供的BtnClick:方法, [self.myview.myBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside]; } //MyView中的按钮的事件 - (void)BtnClick:(UIButton *)btn { NSLog(@"Method in controller."); NSLog(@"Button clicked."); }

5、 AppDelegate.m

#import "AppDelegate.h" #import "MyViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [ [UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds ] ]; MyViewController *myVC = [[MyViewController alloc] init]; self.window.rootViewController = myVC; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }

6、运行结果

界面:

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

输出:

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

总结

以上就是这篇文章的全部内容了,希望能对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新IOS开发学习
热门IOS开发学习
编程开发子分类