Kavin Kumar Arumugam
Kavin Kumar Arumugam

Reputation: 1832

iOS Swift Setting View Frame Position Programmatically

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

Upvotes: 3

Views: 20724

Answers (2)

user4003752
user4003752

Reputation:

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.

Upvotes: 11

Paulo Mattos
Paulo Mattos

Reputation: 19339

If you only want to change the frame Y position, try this instead:

self.SelectClientDetailView.frame.origin.y = 637
self.SelectClientDetailView.frame.origin.y = 837

As already mentioned, you might need to check your view hierarchy to be sure you are actually adding them to the UIScrollView (and not elsewhere).

Upvotes: 10

Related Questions