如何为UIButton添加操作
我是iPhone技术的新手。 请任何人告诉我如何为UIButton添加操作。
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0, 0, 100, 25); btn.backgroundColor = [UIColor clearColor]; [btn setTitle:@"Play" forState:UIControlStateNormal]; [btn addTarget:self action:(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; btn.center = self.center; [self addSubview:btn];
您使用@selector()指定select器。 所以, 动作参数看起来像,
action:@selector(buttonClick:)
用这个
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown]; [button setTitle:@"Show View" forState:UIControlStateNormal]; button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); [view addSubview:button];
action:@selector(buttonClick:)
像这样使用
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0, 0, 100, 25); btn.backgroundColor = [UIColor clearColor]; [btn setTitle:@"Play" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside]; btn.center = self.center; [self addSubview:btn];
并添加你的select器方法
-(IBAction)btnTapped:(id)sender{ }
SWIFT代码:
button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside) ... func action_button() { // implement me }