我有一个分机:

extension UILabel {
    func animateHidden(flag: Bool) {
        self.hidden = flag
    }
}

我需要为UIImageView人制作同样的代码,但我不想复制整个代码.可以为多个类进行扩展吗?

谢谢

推荐答案

你可以制定一个协议并扩展它.

比如:

protocol Animations {
    func animateHidden(flag: Bool)
}

extension Animations {
    func animateHidden(flag: Bool) {
        // some code
    }
}

extension UILabel: Animations {}

extension UIImageView: Animations {}

您的方法将可用于扩展类:

let l = UILabel()
l.animateHidden(false)

let i = UIImageView()
i.animateHidden(false)

在一条 comments 中,你问:"在这种情况下,如何在animateHidden函数中为UILabelUIImageView调用self?".可以通过约束扩展来实现这一点.

where条款为例:

extension Animations where Self: UIView {
    func animateHidden(flag: Bool) {
        self.hidden = flag
    }
}

Thanks to @Knight0fDragon for his excellent comment about the 100 clause.

Swift相关问答推荐

通过withstickedContinuation传递通用类型T

在列表项内的NavigationLink中的按钮无法正常工作

@ MainActor + Combine不一致的编译器错误

VisionOS发送通知

向文本元素添加背景色失败

如何在SWIFT中轻松格式化公制和英制使用的UnitVolume

了解SWIFT中的任务行为

在NavigationStack上设置拐角半径:SwiftUI中的无响应内容视图区

类型擦除`AsyncMapSequence, Element>`

闭包 - deinit self 对象的时间

SwiftUI - Select 器没有 Select 值

Swift UI 不重绘 NSViewRepresentable 包装的文本字段

在视图中设置所有变量

使用 Swift 在 iOS 8 中为应用程序图标添加徽章

在 UItextfield 的右视图上添加一个按钮,文本不应与按钮重叠

Swift中switch 盒的详尽条件

如何在 Swift 中遍历 struct 属性?

TabView 在切换选项卡时重置导航堆栈

使用 swift IOS 使 UIBarButtonItem 消失

NSLocationWhenInUseUsageDescription 警告,但我已经添加了