Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Generate an "X" amount of buttons, based on the amount of buttons specified by online data.

I'm trying to understand, how you can generate a certain amount of buttons depending on data received from online.

The concept I'm thinking of is something similar to how the Facebook newsfeed works.

You can keep scrolling depending on the amount of buttons indicated from online data, and then perform a specific action depending on the button pressed.

This would be similar to the playlist app built in the iOS track but have a variable amount of buttons instead of the hardcoded 6.

1 Answer

When you want to generate an indeterminate amount of UI objects you must do it programatically, in the playlist course the UI objects were created through interface builder, but that's not an option when you don't know how many elements will be created. Generally this task is achieved by reading the amount of elements that will be needed from a web service, and then in a loop you create one element at a time to populate the user interface. In case you are curious about how that code look like I left this snippet from stackoverflow to create an UIButton programatically with Target Action

override func viewDidLoad() {
    super.viewDidLoad()

    let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.frame = CGRectMake(100, 100, 100, 50)
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Test Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

    self.view.addSubview(button)
}  

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

Within viewDidLoad method a button is created and its properties are set, like backgroundColor and title. The function buttonAction is attached to the button so that when is clicked, the message will appear in the console.