How can I create a popover which contains a scrollView automatically scrolled to the top?

1.3k views Asked by At

I am presenting a popover like this:

    let popoverContent = (self.storyboard?.instantiateViewController(withIdentifier: segueIdentifiers.informationPopover))! as UIViewController
    let nav = UINavigationController(rootViewController: popoverContent)
    nav.modalPresentationStyle = UIModalPresentationStyle.popover
    let popover = nav.popoverPresentationController
    popoverContent.preferredContentSize = CGSize(width: 500,height: 600)
    popover?.delegate = self
    popover?.sourceView = self.view
    popover?.sourceRect = CGRect(x: 0, y: 0, width: 100, height: 100)

    self.present(nav, animated: true, completion: nil)

and

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}

The popover being created is from a viewController created in the storyboard.

The viewController with the popover is created has the following layout.

--View
---Scroll View
----View
-----Text View

I initially had a problem where there was an awkward amount of space in between the top of the container and the Text View. Using this link I saw I could remove the Adjusts Scroll View Insets. That fixed the awkward spacing at the top issue but when the scrollView presents itself, it is still scrolled a third of the way down and some of the text at the top is hidden.

Issue: The scrollView is a third of the way scrolled down when it is presented.

Questions: Is there a way to initialize the scrollView to be automatically scrolled at the top using the storyboard, i.e., a run-time attribute? If not, how can I do this programmatically since I am creating the popover programmatically via a storyboard ID?

Update 1 I tried subclassing my viewController and creating an outlet for the scrollView. In my viewDidLoad, viewWillAppear, viewDidLayoutSubviews, viewDidAppear, and viewWillLayoutSubviews I tried the below code. This did not solve my issue.

let scroll2TopOffset = CGPoint(x: 0, y: 0)
self.aboutUsScrollView.setContentOffset(scroll2TopOffset, animated: true)
1

There are 1 answers

0
Sami On BEST ANSWER

Solution: The textView needs to have its scrolling turned off in the viewDidLoad and then turned back on in the viewDidAppear

class AboutUsViewController: UIViewController {
    @IBOutlet weak var aboutUsTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        aboutUsTextView.isScrollEnabled = false
    }

    override func viewDidAppear(_ animated: Bool) {
        aboutUsTextView.isScrollEnabled = true
    }
}

Will leave question open - would like to know if there is a better way of doing this.