1

this is my code

class ViewController: UIViewController {

@IBOutlet weak var d: UIScrollView!
let numberOfButtons = 50

override func viewDidLoad() {

    super.viewDidLoad()
    for index in 0..<self.numberOfButtons {
        let frame1 = CGRect(x: 20 + index, y: 20 + index, width: 45, height: 45 )
        let button = UIButton()
        button.frame = frame1
        button.titleLabel?.text = "asdfasdf"
        self.d.addSubview(button)
    }
}

pretty simple, when i run the simulation, i can't see any button in my scroll view.

i am doing this because i need just to have a scroll view that has more items than the simulate can have, just to check the scroll thing

4
  • You are assigning the title incorrectly. Commented Sep 8, 2015 at 23:17
  • You should use the setTitle method, so: button.setTitle("asdfasdf", forState: .Normal), but honestly the way you're doing it works, it probably won't solve your problem to change it. Commented Sep 8, 2015 at 23:21
  • @TheBeanstalk okay i did that but still nothing appear on my view Commented Sep 8, 2015 at 23:21
  • try let button = UIButton(frame: frame1) Commented Sep 8, 2015 at 23:29

1 Answer 1

8

You just need to set the background color (or the text color), right now they're both white, so it looks like they aren't being drawn. Your code would look like this:

@IBOutlet weak var d: UIScrollView!
let numberOfButtons = 50

override func viewDidLoad() {

    super.viewDidLoad()
    for index in 0..<self.numberOfButtons {
        let frame1 = CGRect(x: 20, y: 20 + (index * 45), width: 45, height: 45 )
        let button = UIButton(frame: frame1)
        button.setTitle("asdfasdf", forState: .Normal)
        button.backgroundColor = UIColor.blackColor()
        self.d.addSubview(button)
    }

}

I've also changed the frames a bit so they'll draw in a straight line down the scroll view. Also, your view will not scroll unless you set the contentSize correctly, so you'll need to throw in a line immediately after the for-loop like this: self.d.contentSize.height = CGFloat(45*numButtons)

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

2 Comments

Yes, this is right. Lol. Plus, your buttons will all be on top of each other. But each to their own, well not on top of each other but 1 pixel apart
okay it worked, but the scroll view didn't scroll. why please? it is already enabled scrolled vertically and horizontally

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.