UIButton as subview for UIScrollView

Hello guys,


I want to have a scroll view containig a button as a subview. My current code looks like this:

buttonScrollView.frame = CGRect(x: 0, y: navigationBar.frame.maxY, width: width, height: height * 0.0809)
 buttonScrollView.backgroundColor = GRAY_COLOR
 buttonScrollView.isScrollEnabled = true


let allButton = UIButton()
allButton.frame = CGRect(x: buttonScrollView.frame.origin.x, y: buttonScrollView.frame.origin.y, width: buttonScrollView.frame.width, height: buttonScrollView.frame.height)
allButton.setTitle("#All", for: .normal)
allButton.setTitleColor(DARK_BLUE_COLOR, for: .normal)
allButton.backgroundColor = UIColor.white
        

buttonScrollView.contentSize = CGSize(width: allButton.frame.width, height: allButton.frame.height)
        
 // add buttons as subviews to scroll view
buttonScrollView.addSubview(allButton)

However, if I add the scroll view to the main view, I can see the scroll view, at least the gray color of the background, but I don't see the button.

First, I thought this has something to do with the frames but if you look at the frame of the allButton, you can see it has the same frame as the scroll view so I don't know what is wrong.


Could anyone help me, please?

On line 1, what are height and width values ?

How do you initialize buttonScrollView ? Why not call UIScrollView(frame:)



So you make the button frame equal to scrollView frame.

And scrollView content size equal to button size, hence equal to its own frame size.

Nothing will scroll.


But most important, the frame of UIButton is relative to the scrollView, so if you want the button to use the whole scrollView frame (which would be curious), you should have something like this


allButton.frame = CGRect (x: 0, y: 0, width: buttonScrollView.frame.width, height: buttonScrollView.frame.height)


Finally, why don't you create objects in IB, that's much easier.

UIButton as subview for UIScrollView
 
 
Q