如何在swift中对约束使用if else语句

时间:2016-09-02 04:07:01

标签: swift colors swift2 constraints move

下面的代码在按下时有一个uicolor框,盒子变成一个较小的uicolor框。问题是只能按一次颜色框。因此盒子可以从大到小但不能从小到大。如何编写代码,以便在单击框时,每次都会将框从大到小或从小到大。

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.
    }


}

1 个答案:

答案 0 :(得分:0)

您正在以笨拙的方式调整视图大小。不要使用约束,不要放置它们。告诉视图在哪里使用它的框架。如果您需要视图来为帧之间的更改设置动画,请使用UIView.animateViewWithDuration()并在函数内部执行您想要的帧更改。这样可以保持过渡平稳,完全掌控。在运行期间,约束并不像帧那样容易实现。