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

5
  • 2
    it looks like it showing Optional("yourData"). have you tried to unwrap it? Commented Apr 13, 2016 at 1:49
  • Good catch but overlapping issue still remains. How can I spread it horizontally in an equal distribution? Commented Apr 13, 2016 at 2:04
  • You should edit your question and state that there is overlapping issue. Commented Apr 13, 2016 at 2:09
  • Use a UIStackView to space items equally either horizontally or vertically. Commented Apr 13, 2016 at 2:17
  • To spread it horizontally, modify x instead of y... Commented Apr 13, 2016 at 2:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. What is optional binding? like if let _ = value {} or guard?
using if let should be sufficient in your case. If you are interested in the comparison between those two, you might want to read stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.