iOS Swift Scrollview Set Frame Position Programmatically

5.5k Views Asked by At

I am have scrollview in my app. By default y position of my scrollview is 80. In some locations I need to move y position of my scrollview to 0. Here is the code

@IBOutlet weak var ScrollView: UIScrollView!
override func viewDidLoad()
{
   super.viewDidLoad()
   self.ScrollView.delegate = self
   if(Position == "changed")
   {
      self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   }
   else
   {
      self.ScrollView.frame = CGRect(x: 0, y: 80, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   }
}

But this code won't works.

2

There are 2 best solutions below

1
Kavin Kumar Arumugam On BEST ANSWER

We will not able to set Scrollview Position in viewDidLoad() so Add those code in viewDidAppear(). Final Code Here

override func viewDidAppear(_ animated: Bool)
{
     DispatchQueue.main.async
     {
          self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height + 80)
     }
}
3
Anbu.Karthik On

problem is simple your VC.view not updated in Viewdidload, so in here you need to move the UI updation on Viewdidappear or update the UI in main thread

by default your self.ScrollView.frame is started in O position, so only check with !=

override func viewDidLoad()
{
   super.viewDidLoad()
   self.ScrollView.delegate = self
   //self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   if(Position != "changed")
   {
     DispatchQueue.main.async {
        self.ScrollView.frame = CGRect(x: 0, y: 80, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
    }

   }

}