Search code examples
iosswiftuiscrollviewuikit

UIScrollView does not scroll in customView


I'm making a custom view and it contains a UIScrollView. But this scroll view does not scroll.

The view hierarchy is as follows:

- mainView
    - UIScrollView
        - contentView

A picture for illustration purposes

Here is my custom view code:

class MyCustomView: UIView {

    @IBOutlet var mainView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var scrollViewContetnView: UIView!

    // MARK: - Methods

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.customInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.customInit()
    }

    // MARK: Custom

    func customInit() {
        Bundle.main.loadNibNamed("EmoKeyboard", owner: self, options: nil)
        self.addSubview(mainView)
        self.mainView.frame = self.bounds
        self.mainView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    func makeTabItem(count: Int) {
        for i in 0...count {
            let icon = UIButton()
            icon.frame.size = CGSize(width: 28, height: 28)
            icon.center.y = self.scrollViewContentView.center.y
            icon.frame.origin.x = 10 + (CGFloat(i) * 28) + (CGFloat(i) * 10)
            icon.backgroundColor = UIColor.black

            self.scrollViewContentView.addSubview(icon)
        }
    }

}

What am I doing wrong?


Solution

  • You have to manually set contentSize of your scrollView based on buttons count or for every button add constraints. Another possible(!) easier way is adding UIStackView as subview of your scrollView and add each button with height/width constraints to it.