0

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.

GingerHead
  • 8,130
  • 15
  • 59
  • 93
Jesse
  • 1
  • 1
  • 1
  • It's important to distinguish "in Xcode" from "using the API". Xcode is the IDE - the program that helps you organize, compile, build, and package programs you write; Cocoa is the API - the toolkit of ready-made objects and system interfaces you use to write applications for the Mac OS and iOS platforms; Objective-C is the primary language in which the Cocoa frameworks and applications based upon them are written. – Joshua Nozzi Jan 17 '11 at 23:34

2 Answers2

3

See "How do I create a basic UIButton programmatically". See also the Target / Action mechanism.

Community
  • 1
  • 1
Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135
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];

Further information here

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

kgutteridge
  • 8,727
  • 1
  • 18
  • 23