Search code examples
iosswiftuiviewuiviewcontrolleruiscrollview

ScrollView is not showing custom UIView


I've tried a lot of solutions asked in the similar questions on stackoverflow but they are either outdated or are not working. I've added a UIScrollView on my UIViewController and made a custom .xib where I've created my long (1336 height) view and want to show it on the scrollView. So in ViewDidAppear() I've added this:

scrollView.contentSize = CGSize(width: self.view.frame.width, height: 1500)
scrollView.addSubview(mainView)

Declared let mainView: MainView = MainView() on top of the class. When I run it, the scroll view just shows blank with no subview but swiping up shows the vertical scroll bar which means the height 1500 is working but the subview is not showing.


Solution

  • let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: <ViewName>, bundle: bundle)
    let mainView = nib.instantiateWithOwner(self, options: nil).first as! MainView
    

    Explanation :

    To instantiate xib above format is used. Please try this and then add it to your UIScrollView.

    Let me know it it worked

    Update: To set the custom frame, we need to give frame to mainview object..

    mainView.frame = scrollView.bounds