3

Using Autolayout, everytime I call bringSubviewToFront, the UIView resets.

I tried setting an original position with txtViewPosition:

        txtViewPosition = CGRect(x: txtView.frame.origin.x, y: txtView.frame.origin.y, width: txtView.frame.size.width, height: txtView.frame.size.height)
        containerView.bringSubviewToFront(txtView)
        txtView.frame = txtViewPosition!
        

It looks like the view is the correct position, but it is still showing up in its original spot (set in AutoLayout).

Update (UIView still snaps back)

override func viewDidLayoutSubviews() {
    if txtViewPosition != nil {
        println("txt position is \(txtViewPosition)")
        txtView.frame = txtViewPosition!
    }
}
Community
  • 1
  • 1
Onichan
  • 4,476
  • 6
  • 31
  • 60
  • It doesn't matter how you adjust the frame, auto layout will reset the frame on the next `-layoutSubviews`. See [When is layoutSubviews called?](http://stackoverflow.com/questions/728372/when-is-layoutsubviews-called) for an explanation of when this happens (note: `-setFrame:` and `bringSubviewToFront` cause it). – Jeffery Thomas Mar 13 '15 at 00:07

2 Answers2

2

If you need to have finer grain control over the layout then you need to makes the changes in -layoutSubviews or -viewDidLayoutSubviews.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • So I need to edit the layoutSubviews each time i call `bringSubviewToFront`? – Onichan Mar 13 '15 at 02:45
  • I'm not sure what you're asking. To clarify, `-layoutSubviews` and `-viewDidLayoutSubviews` are called each and every time a view changes its layout. These callbacks are where you should set your frames. – Jeffery Thomas Mar 13 '15 at 10:48
  • I decided to make the change: `txtView.frame = txtViewPosition!` in `-viewDidLayoutSubviews` since it's called after `-layoutSubviews`. However, the view still snaps back to the original location. – Onichan Mar 13 '15 at 21:07
0

Both view.bringSubviewToFront(txtView) and view.sendSubviewToBack(txtView) reset view position if you animate the view position instead of the constraints. You can use txtView.layer.zPosition instead. The default value is 0. Giving a higher number will bring the view to front.

Artin
  • 241
  • 4
  • 9