Search code examples
iosswift3uiscrollviewcgrectcgrectmake

iOS Swift Scrollview Set Frame Position Programmatically


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.


Solution

  • 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)
         }
    }