如何通过代码触发按钮,在 Xcode 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4718990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:06:15  来源:igfitidea点击:

How to trigger a button through code, in Xcode

iphonexcodeuibuttonactionprogrammatically-created

提问by Jesse

In an iPhone app I am working on, I need to place buttons in a UIScrollView, but because of the fact that I need to place so many buttons to scroll through, I cannot place them in interface builder. Therefore I am having to put them all in the Scroll View through my code. How can I create a button in code, and then use it to trigger an action.

在我正在开发的 iPhone 应用程序中,我需要在 UIScrollView 中放置按钮,但由于我需要放置如此多的按钮来滚动浏览,因此我无法将它们放置在界面构建器中。因此,我不得不通过我的代码将它们全部放在滚动视图中。如何在代码中创建一个按钮,然后用它来触发一个动作。

回答by kgutteridge

  UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  //position button
  myButton.frame = CGRectMake(50, 50, 50, 50); 
  [myButton setTitle:@"Click" forState:UIControlStateNormal];
  // add targets and actions
  [myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
   // add to a view
   [self.view addSubview:myButton];

Further information here

更多信息在这里

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html