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

agg*_*n64 104 iphone objective-c uibutton ios programmatically-created

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

Nic*_*ver 222

试试这个:

斯威夫特4

myButton.addTarget(self,
                   action: #selector(myAction),
                   for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

Objective-C的

[myButton addTarget:self 
             action:@selector(myAction) 
   forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

您可以在Apple的文档中找到丰富的信息来源.看看UIButton的文档,它将揭示UIButton是UIControl的后代,它实现了添加目标的方法.

-

你需要注意是否添加结肠或不后myActionaction:@selector(myAction)

这是参考


Gla*_*ves 23

快速回答:

myButton.addTarget(self, action: "click:", for: .touchUpInside)

func click(sender: UIButton) {
    print("click")
}
Run Code Online (Sandbox Code Playgroud)


小智 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];
Run Code Online (Sandbox Code Playgroud)


iOS*_*per 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 }
Run Code Online (Sandbox Code Playgroud)


kru*_*inh 8

试试这个:

首先在viewcontroller的.h文件中写这个

UIButton *btn;
Run Code Online (Sandbox Code Playgroud)

现在将它写在viewcontrollers 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];
Run Code Online (Sandbox Code Playgroud)

将此视图写在视图控制器的.m文件中的viewDidLoad方法之外

- (IBAction)btnClicked:(id)sender
{
   //Write a code you want to execute on buttons click event
}
Run Code Online (Sandbox Code Playgroud)


San*_*Ram 6

对于Swift 3

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

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

button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)