通過程式碼向 UIButton 新增操作(以程式設計方式)

要向按鈕新增方法,請首先建立一個操作方法:

Objective-C

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

迅速

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

現在要將此操作方法新增到按鈕,你必須編寫以下程式碼行:

目標 C.

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

迅速

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

對於 ControlEvents 引數,ENUM UIControlEvents 的所有成員都有效。