我想创建如下的动画,我在iOS 11.2中完成了这个。
我在iOS 8.4和9.2中测试了这一点 - broke
我将UIButton子类化。添加了RoundedCorner和DropShadow协议。它包含一个关注动画的animateButton函数。
class RoundedShadowButton: UIButton, RoundedCorner, DropShadow {
var originalSize: CGRect?
func animateButton(shouldLoad: Bool, withMessage message: String?) {
let spinner = UIActivityIndicatorView()
spinner.activityIndicatorViewStyle = .whiteLarge
spinner.color = .darkGray
spinner.alpha = 0.0
spinner.hidesWhenStopped = true
spinner.tag = 21
if shouldLoad {
self.addSubview(spinner)
self.setTitle("", for: .normal)
UIView.animate(withDuration: 0.2, animations: {
self.setRoundedCorners(radius: self.frame.height / 2)
self.frame = CGRect(x: self.frame.midX - (self.frame.height / 2), y: self.frame.origin.y, width: self.frame.height, height: self.frame.height)
}, completion: { (finished) in
if finished {
spinner.startAnimating()
spinner.center = CGPoint(x: self.frame.width / 2 + 1, y: self.frame.width / 2 + 1)
spinner.fadeTo(alphaValue: 1.0, withDuration: 0.2)
}
})
self.isUserInteractionEnabled = false
} else {
self.isUserInteractionEnabled = true
// remove spinner
for subView in self.subviews {
if subView.tag == 21 {
subView.removeFromSuperview()
}
}
// return back to original button
UIView.animate(withDuration: 0.2, animations: {
if let size = self.originalSize {
self.setRoundedCorners(radius: 8)
self.frame = size
self.setTitle(message, for: .normal)
}
})
}
}
}
protocol RoundedCorner {}
extension RoundedCorner where Self: UIView {
func setRoundedCorners(radius: CGFloat) {
layer.cornerRadius = radius
}
}
protocol DropShadow {}
extension DropShadow where Self: UIView {
func setShadow(width: CGFloat = 0, height: CGFloat = 0, opacity: Float, radius: CGFloat, color: UIColor) {
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = CGSize(width: width, height: height)
layer.shadowRadius = radius
}
}
在HomeVC的viewDidAppear中,我设置了角半径,阴影和帧大小。在IBAction按钮中,我调用了animate函数。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
actionBtn.originalSize = actionBtn.frame
actionBtn.setRoundedCorners(radius: 8)
actionBtn.setShadow(opacity: 0.3, radius: 10.0, color: .darkGray)
}
@IBAction func actionBtnTapped(_ sender: Any) {
self.actionBtn.animateButton(shouldLoad: true, withMessage: nil)
}
如何解决这个问题?
答案 0 :(得分:2)
使用约束制作动画时,您还需要使用约束。虽然它有时可能有效,但它不是你可以依赖的东西。你可以这样解决它。
leading
和trailing
约束。same width
宽度限制为superview
减去40
。将其连接到名为NSLayoutConstraint
的{{1}}类型的类变量。设置优先级widthConstraint
。750
设置为与高度相同,因此它变为圆形。将优先级设置为width
。500
。{/ li>中向center
添加约束
现在,在您的代码中替换帧修改部分。
superview
有了这个。通过更改优先级,您可以选择应该生效的约束。由于宽约束是750,它将胜过狭窄约束。将优先级更改为250时,窄约束将获胜。
self.frame = CGRect(x: self.frame.midX - (self.frame.height / 2), y: self.frame.origin.y, width: self.frame.height, height: self.frame.height)
答案 1 :(得分:0)
试试这个,我的工作只是禁用它:
self.view.translatesAutoresizingMaskIntoConstraints = false