【问题标题】:How to use a if else statement on constraints in swift如何在swift中对约束使用if else语句
【发布时间】:2016-09-02 04:07:00
【问题描述】:

下面的代码在按下时有一个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.
    }


}

【问题讨论】:

标签: swift colors swift2 constraints move


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多