FirstApp,iphone开发学习总结3,UIButton简单的操作

相同的,为了Tab init:

- (id)init {
    self = [super init];
    if (self) {
        [self setTitle:@"按钮展示"];
        
        UIImage *img = [UIImage imageNamed:@""];
        [[self tabBarItem] setImage:img];
    }
    return self;
}

在- (void)viewDidLoad中,创建2个按钮(Left and Right),设置Left的Tag为0,Right的Tag为1(区分谁点击),点击执行onClick事件:

- (void)viewDidLoad
{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    leftBtn.frame = CGRectMake(40.0100.0100.030.0);
    [leftBtn setTitle:@"Left" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTag:0];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightBtn.frame = CGRectMake(180.0100.0100.030.0);
    [rightBtn setTitle:@"Right" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTag:1];
   
    [[self view] addSubview:leftBtn];
    [[self view] addSubview:rightBtn];
}

添加onClick://@selector(onClick:),添加了:,如果事件为- (void)onClick,则不需要添加

- (void)onClick:(UIButton *)sender
{
    switch ([sender tag]) {
        case 0:
            [self alert:@"左键"];
            break;
        case 1:
            [self alert:@"右键"];
            break;
    }
}

添加alert方法:

- (void)alert:(NSString *)str
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您点击了" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
    [alert show];
    [alert release];
}


实现的效果就是谁点击,提示谁。

求指点。

原文地址:https://www.cnblogs.com/maxfong/p/2481951.html