天天看点

UIBUTTON点击事件

#import "Person.h"

@implementation AppDelegate

- (void)dealloc

{

    [_arr release];

    [self.window release];

    [super dealloc];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    //按钮实例化

    UIButton *b = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    b.frame = CGRectMake(0, 20, 50, 50);

    // 给按钮设置标题(普通状态下)

    [b setTitle:@"1" forState:UIControlStateNormal];

    // 修改标题颜色

    [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    // 高亮状态下的标题

    [b setTitle:@"2" forState:UIControlStateHighlighted];

    // 按钮不可被点击的状态

    [b setTitle:@"3" forState:UIControlStateDisabled];

    //按钮不可接受点击事件

//    b.enabled = NO;

    //按钮的事件机制

    //添加点击事件

    //UIControlEventTouchUpInside 按下并且抬起

    //必须要实现@selector方法 不实现崩溃

    //成员变量不能使用加方法

    //正确写法

    _arr = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];

    _arr = [[[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil] retain];

    //Person *p =[[Person alloc] init]; 在addTarget调用Person对象的话,会触发Person的click方法

    [b addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    [self.window addSubview:b];

    return YES;

}

bool flag = 0;

-(void)click

{

    NSLog(@"click");

    if (flag) {

        self.window.backgroundColor = [UIColor blackColor];

    }else{

        self.window.backgroundColor = [UIColor whiteColor];

    }

    flag = !flag;

}