我正在尝试扩展多个类,即UIButton和UITextField。它们都具有相同的功能,在我调用该功能时可以摆动。我试图不重复我的代码不止一次。我一直在尝试使用protocal,以便可以扩展并编写所需的函数,然后在类中对其进行扩展,但是问题出在我的函数中,我必须调用self,但是由于self可以仅在UITextField和UIButton上调用。
这是我的代码
import UIKit extension UIButton { func wiggle() { let position = "position" let wiggleAnimation = CABasicAnimation(keyPath: position) wiggleAnimation.duration = 0.05 wiggleAnimation.repeatCount = 5 wiggleAnimation.autoreverses = true wiggleAnimation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y) wiggleAnimation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y) layer.add(wiggleAnimation, forKey: position) } } extension UITextField { func wiggle() { let position = "position" let wiggleAnimation = CABasicAnimation(keyPath: position) wiggleAnimation.duration = 0.05 wiggleAnimation.repeatCount = 5 wiggleAnimation.autoreverses = true wiggleAnimation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y) wiggleAnimation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y) layer.add(wiggleAnimation, forKey: position) } }
这是我尝试尝试的操作,但由于我打电话给自己而出现错误。
protocol Animations { func wiggle() } extension Animations { func wiggle() { let position = "position" let wiggleAnimation = CABasicAnimation(keyPath: position) wiggleAnimation.duration = 0.05 wiggleAnimation.repeatCount = 5 wiggleAnimation.autoreverses = true wiggleAnimation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y) wiggleAnimation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y) layer.add(wiggleAnimation, forKey: position) } } extension UIButton: Animations {} extension UITextField: Animations {}
我收到的错误是'Self'类型的值没有成员'center''Self'类型的值没有成员'center'使用了未解析的标识符'layer'
仅UIView
具有中心属性。对于Swift 5+,您的协议声明应如下所示:
protocol Animations: UIView { func wiggle() }
注意只有UIViews才能符合此协议。
对于Swift 4.x,您必须像这样使用它:
protocol Animations { func wiggle() } extension Animations where Self: UIView { func wiggle() { let position = "position" let wiggleAnimation = CABasicAnimation(keyPath: position) wiggleAnimation.duration = 0.05 wiggleAnimation.repeatCount = 5 wiggleAnimation.autoreverses = true wiggleAnimation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y) wiggleAnimation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y) layer.add(wiggleAnimation, forKey: position) } }