da1lbi3 da1lbi3 - 5 months ago 12
iOS Question

Change view and change it the the original later after autolayout xcode

I have this view in my storyboard:

enter image description here

When I push on button the view needs to animate. What I want is that textbox with placeholder 1 dissapears. Textbox with placeholder 2 must float to position of the first textbox and the view (green background) must get a different height. After that it needs to change back in this view.

I have this code:

import UIKit

class ViewController : UIViewController, UISearchBarDelegate {

@IBOutlet weak var heightView: NSLayoutConstraint!
@IBOutlet weak var tlabel: UILabel!
@IBOutlet weak var mview: UIView!
@IBOutlet weak var t2: UITextField!

@IBOutlet weak var t1: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func test(sender: AnyObject) {
self.mview.translatesAutoresizingMaskIntoConstraints = false;
self.t2.translatesAutoresizingMaskIntoConstraints = false;

UIView.animateWithDuration(0.5, animations: {
self.mview.frame = CGRectMake(0, 0, 320, 80);

self.t2.frame = CGRect(x: 20, y: 0, width: 10, height: 80);
})

self.t1.hidden = true
}
}


t1 is the first textbox, t2 the second. mview is the view with the green background.

enter image description here

This is what I get after I pushed the button.

The textbox must go more to the top. How can I do this? And is there a way to go back to the original view in my storyboard?

What I want is this: When the user taps on a textbox the animation must fire, they can type and get related search results under the green area. When the user selects an row in the table it must go back to the view in the storyboard and fill in the selected value.

**Found the solution:**
import UIKit

class ViewController : UIViewController, UISearchBarDelegate {
var c1 : CGFloat = 0;
var c2 : CGFloat = 0;

@IBOutlet weak var mview: UIView!
@IBOutlet weak var t1: UITextField!
@IBOutlet weak var t2: UITextField!


@IBOutlet weak var vcc: NSLayoutConstraint!
@IBOutlet weak var jj: NSLayoutConstraint!

override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func test(sender: AnyObject) {
c1 = self.jj.constant;
c2 = self.vcc.constant

self.jj.constant = 0;
self.vcc.constant = 80
}

@IBAction func original(sender: AnyObject) {
self.vcc.constant = c2
self.jj.constant = c1

}
}

Answer

This is my suggestion:

  1. remove height constraint from mview(the green view)
  2. add height constraint to t1
  3. add vertical distance constraint between t1 and t2
  4. add vertical constraint t2's bottom and mview' bottom

then

@IBAction func test(sender: AnyObject) {
    self.t1.heightConstraint.constant = 0
    self.view.setNeedsLayout()
    UIView.animateWithDuration(0.5, animations: {
        self.view.layoutIfNeeded()
    })
}

if you want to go back to origin view, change the value of self.t1.heightConstraint.constant

hope it's helpful

Comments