iOS Swift Setting View Frame Position Programmatically

Kavin Kumar Arumugam picture Kavin Kumar Arumugam · Apr 27, 2017 · Viewed 16.4k times · Source

I having two sub views inside scrollview. I need to position that both subviews programmatically. I did it correctly by writing code inside DispatchQueue.main.async. Here is the code:

DispatchQueue.main.async {
    self.SelectClientDetailView.frame = CGRect(x: 0, y: 637, width: self.SelectClientDetailView.frame.size.width, height: self.SelectClientDetailView.frame.size.height)
    self.SelectClientDetailView2.frame = CGRect(x: 0, y: 837, width: self.SelectClientDetailView2.frame.size.width, height: self.SelectClientDetailView2.frame.size.height)
}

Its working good but when I scrolling my scrollview this both views set back to old positions. How to fix it. Its Default y position will be SelectClientDetailView:400 and SelectClientDetailView2: 600

Answer

RMRAHUL picture RMRAHUL · Apr 27, 2017

If you are using Auto Layout then setting frame will cause some weird effects. Auto Layout and Frames doesn't go together. You'll need to rearrange the constrains, not the frames. While using Auto Layout changing the frames will cause some weird effects and will eventually revert back to the constraints you've created in the original UIView.

Some solutions:

  1. If you want to use Autolayout approach then, You need to create an outlet to each constrain just like you would to a view and change its constant when needed.
  2. disable Auto Layout in that specific xib and start playing with frames.