热门标签 | HotTags
当前位置:  开发笔记 > IOS > 正文

如何使用Swift4/5扩展多个类

如何解决《如何使用Swift4/5扩展多个类》经验,为你挑选了1个好方法。

我正在尝试扩展多个类,即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'



1> Teetz..:

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)
    }
}


推荐阅读
author-avatar
小林2502927313
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有