Jesse
Jesse

Reputation: 1

How to trigger a button through code, in Xcode

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.

Upvotes: 0

Views: 8060

Answers (2)

kgutteridge
kgutteridge

Reputation: 8981

  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

Upvotes: 3

Related Questions