【发布时间】:2018-02-17 12:33:39
【问题描述】:
我想创建如下动画,我是在 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
}
}
DropShadow
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
在 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)
}
如何解决?
【问题讨论】:
-
您的前导/尾随约束很可能会阻止它调整大小。虽然它有效,但它不是你可以依赖的东西。使用约束时,您还需要使用约束来调整项目的大小。
-
@Sh_Khan 无效
-
@LGP 我将优先级更改为 999,但没有帮助。你身边的任何想法
-
在下面查看我的解决方案。
-
只需检查它没有约束并手动处理(意味着删除所有约束)。它会工作
标签: ios swift animation uiview autolayout