如何在Xcode中以编程方式向按钮添加操作

108

我知道如何通过从界面构建器拖动添加一个IBAction到按钮中,但是我想通过编程方式添加操作来节省时间并避免不断地来回切换。解决方案可能非常简单,但当我搜索时似乎找不到任何答案。谢谢!

10个回答

227
尝试这个:

Swift 4

myButton.addTarget(self,
                   action: #selector(myAction),
                   for: .touchUpInside)

Objective-C

[myButton addTarget:self 
             action:@selector(myAction) 
   forControlEvents:UIControlEventTouchUpInside];

你可以在苹果的文档中找到丰富的信息。看一下UIButton的文档,它会揭示UIButton是UIControl的子类,实现了添加目标方法。

--

action:@selector(myAction)中,你需要注意是否在myAction后面加上冒号。

这里是reference


如果我想在按钮被按下时向选择器传递参数怎么办(例如,我在UITableViewCell中有一个按钮,并且我想在单元格的按钮被按下时传递该单元格中的对象)? - acecapades
1
@acecapades,我认为你把两件事情混淆了。你不能像使用performSelector一样附加一个参数。UIControl的子类UIButton使用的操作模式是在触发controlEvent时通知某个目标使用特定的选择器。当这种情况发生时,您可以向上遍历superviews以查看封装您的按钮的对象,并请求该方法来解析tablecell与model之间的关系,然后对此进行任何想要的处理。 - Nick Weaver
1
我明白了,那很有道理。我想我明白你在说什么。谢谢你的建议,尼克! - acecapades
有人能用 Swift 翻译一下吗? - user3674231

25

在UIControl.addTarget的调用中,“click”后面的“:”是什么意思? - dumbledad
1
选择器有一个冒号作为函数参数的占位符。由于click需要sender参数,因此在选择器字符串中用:替换它。 - Etan
这段代码最近在Swift 3中对我有效。 button.addTarget(self, action: #selector(ViewController.click), for: UIControlEvents.touchUpInside) func click() { print("click") } 感谢@Glauco Neves指引我们找到正确的方向。 - uplearned.com

14
CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
        UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
        [button setTitle: @"My Button" forState: UIControlStateNormal];
        [button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];

能否添加2个或更多的操作? - ErasmoOliveira

9

尝试这个:

首先在您的视图控制器的.h文件中编写以下内容:

UIButton *btn;

现在将以下代码添加到你的视图控制器的viewDidLoad方法中的.m文件中。
btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

在您的视图控制器的.m文件中,将此代码写在viewDidLoad方法之外。
- (IBAction)btnClicked:(id)sender
{
   //Write a code you want to execute on buttons click event
}

8
 CGRect buttonFrame = CGRectMake( x-pos, y-pos, width, height );   //
 CGRectMake(10,5,10,10) 

 UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];

 button setTitle: @"My Button" forState: UIControlStateNormal];

 [button addTarget:self action:@selector(btnClicked:) 
 forControlEvents:UIControlEventTouchUpInside];

 [button setTitleColor: [UIColor BlueVolor] forState:
 UIControlStateNormal];

 [view addSubview:button];




 -(void)btnClicked {
    // your code }

6

对于Swift 3

首先创建一个按钮操作函数,然后将该函数添加到您的按钮目标中。

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)

3
UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];


}

-(void)btnClicked
{
    // Here You can write functionality 

}

请提供一些解释说明您的样例如何有所帮助。 - Nogard
UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom]; btnNotification.frame=CGRectMake(130,80,120,40);//设置按钮框架 btnNotification.backgroundColor=[UIColor greenColor]; [btnNotification setTitle:@"创建通知" forState:UIControlStateNormal];//设置按钮标题 [btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];//添加按钮事件 [self.view addSubview:btnNotification];} -(void)btnClicked { // 在这里编写功能} - user2677311
-(void)btnClicked { //在这里你可以为按钮设置任何操作 //例如:跳转到下一个视图控制器 nextviewController *nextPage=[nextviewController alloc]init]; [self.navigationController pushviewcontroller:nextPage animated:YES ]; } - user2677311

2

UIButton 继承自 UIControl。它具有添加/删除操作的所有方法:UIControl 类参考。请查看“准备和发送操作消息”一节,其中包括 – sendAction:to:forEvent:– addTarget:action:forControlEvents:


1
 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

1

IOS 14 SDK:

您可以添加带有闭包回调的操作:

let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))

获取控件发送者的引用。
let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
    let textField = action.sender as! UITextField
    print("Text is \(textField.text)")
}), for: .editingChanged)

{{链接1:源代码}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接