gpt4 book ai didi

ios - 如何使用 Swift 4/5 扩展多个类

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:14 26 4
gpt4 key购买 nike

我正在尝试扩展多个类,它们是 UIButton 和 UITextField。它们都具有相同的功能,当我调用该函数时它们可以摆动。我尽量不重复我的代码一次以上。我一直在尝试使用可以扩展和编写我想要的函数的协议(protocol),然后在我的类中扩展它们,但问题出在我的函数中,我必须调用 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)
}

}

这是我尝试过的尝试,但由于我正在调用 self,所以出现错误。

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”使用未解析的标识符“层”

最佳答案

只有 UIView 有 center 属性。对于 Swift 5+,您的协议(protocol)声明应如下所示:

protocol Animations: UIView {
func wiggle()
}

注意只有 UIViews 可以符合这个协议(protocol)。

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

关于ios - 如何使用 Swift 4/5 扩展多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57330667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com