swift - 如何在 swift 约束上使用 if else 语句

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


}

最佳答案

您正在以一种笨拙的方式调整 View 大小。不要使用约束,不要放置它们。告诉 View 它的框架去哪里。如果您需要 View 为帧之间的变化设置动画,请使用 UIView.animateViewWithDuration() 并在函数内部执行您想要的帧变化。这样可以使过渡顺畅并完全控制在您手中。在运行时,约束不像框架那样容易正确实现。

关于swift - 如何在 swift 约束上使用 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39284144/

相关文章:

swift - 检查字符串是 int 还是 double ,在 swift 3 中有扩展

ios - 更新 View Controller 之间的状态栏样式

css - 将鼠标移到社交图标上时如何更改它们的颜色?

ios - Firebase 不适用于真实设备 (iOS)

ios - 从 iOS 9 开始,应用程序 :openURL:sourceApplication:annotation: is deprecated, 如何在 iOS 8 中使用新方法?

ios - 按比例绘制圆圈以快速包含 View

arrays - 在 Array<AnyObject> 中搜索不区分大小写的字符串

ios - 添加到 MKMapView 时出现 UILongPressGestureRecognizer 问题

python - 彩色图像卷积核的 tensorflow 权重?

colors - 生成 n 色彩虹调色板