Search code examples
iosuiscrollviewuinavigationitem

UIScrollView not displaying in UINavigationItem


In my UIView subclass I added the below init method, and then I'm assigning this view as the titleView on a navigationItem. I see a red rectangle, meaning this view is there, but I don't see the yellow scroll view. What am I doing wrong here?

open class ChatNavBarImagesView : UIView {
    private let scrollView = UIScrollView()

    public init(navigationController: UINavigationController) {
        let height = navigationController.navigationBar.frame.height

        super.init(frame: CGRect(x: 0, y: 0, width: 200, height: height))

        backgroundColor = UIColor.red

        addSubview(scrollView)

        scrollView.leadingAnchor.constraint(equalTo: leadingAnchor)
        scrollView.trailingAnchor.constraint(equalTo: trailingAnchor)
        scrollView.topAnchor.constraint(equalTo: topAnchor)
        scrollView.bottomAnchor.constraint(equalTo: bottomAnchor)

        scrollView.backgroundColor = UIColor.yellow
        scrollView.contentSize = CGSize(width: 200, height: height)
    }

Solution

  • You need to set frame of the scrollView to the bounds of ChatNavBarImagesView

    scrollView.frame = bounds
    addSubview(scrollView)