通过代码向 UIButton 添加操作(以编程方式)

要向按钮添加方法,请首先创建一个操作方法:

Objective-C

 placeholderCopy-(void)someButtonAction:(id)sender {
  // sender is the object that was tapped, in this case its the button.
    NSLog(@"Button is tapped"); 
}

迅速

 placeholderCopyfunc someButtonAction() {
    print("Button is tapped")
}

现在要将此操作方法添加到按钮,你必须编写以下代码行:

目标 C.

 placeholderCopy[yourButtonInstance addTarget:self action:@selector(someButtonAction) forControlEvents:UIControlEventTouchUpInside];

迅速

 placeholderCopyyourButtonInstance.addTarget(self, action: #selector(someButtonAction), forControlEvents: .TouchUpInside)

对于 ControlEvents 参数,ENUM UIControlEvents 的所有成员都有效。