UIControlStateHighlighted
、UIControlStateDisabled
、UIControlStateSelected
以外的其他情况,都是normal状态highlighted = YES
】时就能达到这种状态button.enabled = NO
】时就能达到这种状态button.selected = YES
】时就能达到这种状态button.enabled = NO;
button.userInteractionEnabled = NO;
@interface MyView : UIView@property (strong, nonatomic) UIButton *myBtn;@end2、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;}@end3、MyViewController.h
#import <UIKit/UIKit.h>@interface MyViewController : UIViewController@end4、MyViewController.m
#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:selfaction:@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、运行结果
输出:
总结
以上就是这篇文章的全部内容了,希望能对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。