在 Swift 中呈现微调器的动画按钮

Animating button to present a spinner in Swift

所以我想制作一个按钮在按下时动画转一圈,然后能够将按钮发送回其原始状态。这是我当前的动画,如您所见,我已经完成了一半。

如您所见,我在这里遇到了多个问题。首先,当我设置新约束时,X 约束不会将圆圈放在父视图的中间。然后我最初的想法是,当我调用重置函数时,我也会传递视图的原始约束,但这是行不通的。

我的想法是,当我使用它时,我将放置一个 UIView,然后在该视图内放置按钮,这样我就可以操纵它的约束。如果我在 UIStackView 中放置一个按钮,情况也会如此。

这是我的代码,任何输入都很棒

extension UIButton {

func animateWhileAwaitingResponse(showLoading: Bool, originalConstraints: [NSLayoutConstraint]) {

    let spinner = UIActivityIndicatorView()
    let constraints = [
        NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: self.superview, attribute: .centerX, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 45),
        NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 45),
        NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.superview, attribute: .top, multiplier: 1, constant: 4),
        NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.superview, attribute: .bottom, multiplier: 1, constant: 8),
        NSLayoutConstraint(item: spinner, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: spinner, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: spinner, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 45),
        NSLayoutConstraint(item: spinner, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 45)
    ]

    if showLoading {

        NSLayoutConstraint.deactivate(self.constraints)
        self.translatesAutoresizingMaskIntoConstraints = false
        spinner.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(spinner)
        self.superview?.addConstraints(constraints)
        spinner.color = .white
        spinner.startAnimating()

        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.setTitleColor(.clear, for: .normal)
            self.layer.cornerRadius = 22.5
            self.layoutIfNeeded()
        }, completion: nil)
    } else {
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            NSLayoutConstraint.deactivate(self.constraints)
            self.setTitleColor(.white, for: .normal)
            self.superview?.addConstraints(originalConstraints)
            NSLayoutConstraint.activate(originalConstraints)
            self.layer.cornerRadius = 0

            for subview in self.subviews where subview is UIActivityIndicatorView {
                subview.removeFromSuperview()
            }
            self.layoutIfNeeded()
        }, completion: nil)

      }
   }
}

我注意到您在第一个动画中设置了 self.translatesAutoresizingMaskIntoConstraints = false,但没有在第二个动画中将其设置回 true

这可能是问题的根源:您需要在第二个动画期间设置 self.translatesAutoresizingMaskIntoConstraints = true

如果您在 Interface Builder(或您最初创建按钮的任何地方)中关闭 translatesAutoresizingMaskIntoConstraints,并使用正常约束进行所有布局,可能会减少混淆。

我已经更新了你的按钮扩展代码如下,它是用动画添加和删除约束。

extension UIButton {

    func animateWhileAwaitingResponse(showLoading: Bool, originalConstraints: [NSLayoutConstraint]) {

        let spinner = UIActivityIndicatorView()
        spinner.isUserInteractionEnabled = false

        // Constraints which will add in supper view
        let constraints = [
            NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: self.superview, attribute: .centerX, multiplier: 1, constant: 0),
            NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: self.superview, attribute: .centerY, multiplier: 1, constant: 0),

            NSLayoutConstraint(item: spinner, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0),
            NSLayoutConstraint(item: spinner, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0),
            NSLayoutConstraint(item: spinner, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 45),
            NSLayoutConstraint(item: spinner, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 45)
        ]

        // Constrains which will add in button
        let selfCostraints = [
            NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 45),
            NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 45),
        ]

        // Keeping this outside of condition due to adding constrains programatically.
        self.translatesAutoresizingMaskIntoConstraints = false
        spinner.translatesAutoresizingMaskIntoConstraints = false

        if showLoading {

            // Remove width constrains of button from superview
            // Identifier given in storyboard constrains
            self.superview?.constraints.forEach({ (constraint) in
                if constraint.identifier == "buttonWidth" {
                    constraint.isActive = false
                }
            })

            NSLayoutConstraint.deactivate(self.constraints)

            self.addSubview(spinner)
            self.superview?.addConstraints(constraints)
            self.addConstraints(selfCostraints)
            spinner.color = .white
            spinner.startAnimating()
            spinner.alpha = 0

            UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
                self.setTitleColor(.clear, for: .normal)
                self.layer.cornerRadius = 22.5
                spinner.alpha = 1
                self.layoutIfNeeded()
            }, completion: nil)

        } else {


            UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {

                for subview in self.subviews where subview is UIActivityIndicatorView {
                    subview.removeFromSuperview()
                }

                self.removeConstraints(selfCostraints)
                NSLayoutConstraint.deactivate(self.constraints)
                self.setTitleColor(.white, for: .normal)
                self.superview?.addConstraints(originalConstraints)
                NSLayoutConstraint.activate(originalConstraints)
                self.layer.cornerRadius = 0

                self.layoutIfNeeded()
            }, completion: nil)
        }
    }
} 

我已将以下约束添加到按钮:

此外,添加了按钮宽度约束的标识符以从 super 中删除,这将从原始约束中添加运行时。

然后我通过获取宽度约束的出口以编程方式更改按钮的宽度:

@IBOutlet weak var const_btnAnimation_width : NSLayoutConstraint!

viewDidLoad 方法内部

self.const_btnAnimation_width.constant = UIScreen.main.bounds.width - 40

其中 40 是前导和尾随的总和 space。

点击按钮

@IBAction func btnAnimationPressed(_ sender: UIButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        self.btnAnimation.animateWhileAwaitingResponse(showLoading: true, originalConstraints: sender.constraints)
    } else {
        self.btnAnimation.animateWhileAwaitingResponse(showLoading: false, originalConstraints: self.btnAnimationConstraints)
    }
}

btnAnimationConstraintsNSLayoutConstraint 的数组如下:

var btnAnimationConstraints = [NSLayoutConstraint]()

所以我只是在 viewDidAppear 方法中分配按钮的所有约束,如下所示:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.btnAnimationConstraints = self.btnAnimation.constraints
}

希望对您有所帮助。

输出:

我正在更新代码以设置动态按钮高度并根据按钮父级高度管理圆圈。您可以使用

button.frame.height

围成一圈。

extension UIButton {

func animateWhileAwaitingResponse(showLoading: Bool, originalConstraints: [NSLayoutConstraint]) {

    let spinner = UIActivityIndicatorView()
    spinner.isUserInteractionEnabled = false

    // Constraints which will add in supper view
    let constraints = [
        NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: self.superview, attribute: .centerX, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: self.superview, attribute: .centerY, multiplier: 1, constant: 0),

        NSLayoutConstraint(item: spinner, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: spinner, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: spinner, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: self.frame.height),
        NSLayoutConstraint(item: spinner, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: self.frame.height)
    ]

    // Constrains which will add in button
    let selfCostraints = [
        NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: self.frame.height),
        NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: self.frame.height),
    ]

    // Keeping this outside of condition due to adding constrains programatically.
    self.translatesAutoresizingMaskIntoConstraints = false
    spinner.translatesAutoresizingMaskIntoConstraints = false

    if showLoading {

        // Remove width constrains of button from superview
        // Identifier given in storyboard constrains
        self.superview?.constraints.forEach({ (constraint) in
            if constraint.identifier == "buttonWidth" {
                constraint.isActive = false
            }
        })

        NSLayoutConstraint.deactivate(self.constraints)

        self.addSubview(spinner)
        self.superview?.addConstraints(constraints)
        self.addConstraints(selfCostraints)
        spinner.color = .white
        spinner.startAnimating()
        spinner.alpha = 0

        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.setTitleColor(.clear, for: .normal)
            self.layer.cornerRadius = self.frame.height / 2
            spinner.alpha = 1
            self.layoutIfNeeded()
        }, completion: nil)

    } else {


        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {

            for subview in self.subviews where subview is UIActivityIndicatorView {
                subview.removeFromSuperview()
            }

            self.removeConstraints(selfCostraints)
            NSLayoutConstraint.deactivate(self.constraints)
            self.setTitleColor(.white, for: .normal)
            self.superview?.addConstraints(originalConstraints)
            NSLayoutConstraint.activate(originalConstraints)
            self.layer.cornerRadius = 0

            self.layoutIfNeeded()
        }, completion: nil)
    }
}

}