2016-09-02 66 views
1

下面的代碼在按下時有一個彩色框,框變成一個較小的彩色框。問題是隻能按一次顏色框。所以盒子可以從大到小,但不能從小到大。如何編寫代碼,以便在單擊框時每次都從大到小或從小到大。如何在swift中對約束條件使用if else語句

import UIKit 

class ViewController: UIViewController { 

    let colorview = UIView() 
    var initialc = [NSLayoutConstraint]() 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(ViewController.myFunction(_:))) 
     colorview.userInteractionEnabled = true 
     colorview.addGestureRecognizer(tapGestureRecognizer) 


     colorview.translatesAutoresizingMaskIntoConstraints = false 
     colorview.backgroundColor = UIColor.blueColor() 
     self.view.addSubview((colorview)) 

     let leadingc = colorview.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor) 
     let trailingC = colorview.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor) 
     let topc = colorview.topAnchor.constraintEqualToAnchor(self.view.topAnchor) 
     let bottomc = colorview.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor, constant: -50) 

     initialc.appendContentsOf([leadingc,trailingC,topc,bottomc]) 
     NSLayoutConstraint.activateConstraints(initialc) 


    } 

    func myFunction(sender: AnyObject) { 

     NSLayoutConstraint.deactivateConstraints(initialc) 

     let widthc = colorview.widthAnchor.constraintEqualToConstant(100) 
     let heightc = colorview.heightAnchor.constraintEqualToConstant(100) 
     let centerxc = colorview.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor) 
     let centeryc = colorview.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor) 

     NSLayoutConstraint.activateConstraints([widthc,heightc,centerxc,centeryc]) 

    } 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
+0

您可以繪製一張描述您想要執行哪種動畫/佈局更改的草圖? – ozgur

+0

看到這個問題:http://stackoverflow.com/q/39195484/1630618 – vacawama

回答

0

您正以尷尬的方式調整視圖大小。不要使用約束,不要放置它們。告訴視圖與框架在哪裏。如果您需要視圖來爲框架之間的變化設置動畫效果,請使用UIView.animateViewWithDuration(),並在功能框內更改您希望的框架。這樣可以保持轉換順暢並完全控制在您的手中。限制在運行時不如框架那樣容易實現。