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

时间:2011-01-17 23:25:02

标签: iphone xcode uibutton action programmatically-created

在我正在处理的iPhone应用程序中,我需要在UIScrollView中放置按钮,但由于我需要放置这么多按钮来滚动,我无法将它们放在界面构建器中。因此,我必须通过我的代码将它们全部放在Scroll View中。如何在代码中创建按钮,然后使用它来触发操作。

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:3)

  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];

此处的更多信息

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