2

I have the following code that creates buttons based on the fetched data. After buttons are created they get added to a scrollview. And they should display horizontally.

I can confirm that there is data but it shows weird things in simulator (see attached screenshot). What is wrong in my implementation?

override func viewDidLoad() {
    super.viewDidLoad()

    fetchRecipeCategory()

    for var i = 0; i < self.category.count; i++ {
        let frame1 = CGRect(x: 20, y: 20 + (index * 45), width: 45, height: 45 )
        let button = UIButton(frame: frame1)
        button.setTitle("\(category[i].name)", forState: .Normal)
        button.backgroundColor = UIColor.blackColor()
        self.categoryScrollView.addSubview(button)

    }
    print(category[0].name)
}

enter image description here

Seong Lee
  • 10,314
  • 25
  • 68
  • 106

1 Answers1

2

You need to use different y frame value for each button. Your button creation is using index for its y frame and you did not increment it.

Since your are using for loop, you could use i value for it.

let frame1 = CGRect(x: 20, y: 20 + (i * 45), width: 45, height: 45 )

this code will create vertical list of button. If you want to list your button horizontally, change x frame value for each button

let frame1 = CGRect(x: 20 + (i * 45), y: 20, width: 45, height: 45 )

As for your screenshot, it looks like that the button title is set to Optional("data"). if you really sure that your data source contains data, you could simply unwrap it for your button title. Better if you use optional binding for it.

seto nugroho
  • 1,359
  • 1
  • 13
  • 20
  • Thanks. What is optional binding? like `if let _ = value {}` or guard? – Seong Lee Apr 13 '16 at 02:17
  • using `if let` should be sufficient in your case. If you are interested in the comparison between those two, you might want to read http://stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let – seto nugroho Apr 13 '16 at 02:22