提问者:小点点

如何为多个类Swift进行扩展


我有一个扩展:

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

我需要为UIImageView制作相同的代码,但我不想复制整个代码。是否可以为多个类进行扩展?

谢谢。


共2个答案

匿名用户

您可以制定协议并对其进行扩展。

像这样的东西:

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)

在评论中,您问:“在这种情况下,如何在动画隐藏函数中为UILabelUIImageView调用self?”。您可以通过约束扩展来做到这一点。

带有where子句的示例:

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

感谢@Knight 0fDragon对where子句的精彩评论。

匿名用户

在您的情况下,更好的方法是扩展UIView。这是因为UILabelUIImageView都继承自UIView

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

标签和图像的声明View:

label = UILabel()
imageView = UIImageView()

扩展的实际用法

label.animateHidden(flag: true)
imageView.animateHidden(flag: false)

如果您希望您的扩展能够符合许多不同类型的UI组件,那么有4种类型的UI组件符合:

  1. C Var Arg
  2. E qua table
  3. 可哈希
  4. NS编码

许多UI组成部分包括:

>

  • UILabel:CVarArgEquableHas可散列NSCoding

    UITextField:CVarArgEquable可散列NSCoding

    UITableViewCell:CVarArgEquableHasableNSCoding

    UITextView:CVarArgEqu可转换可散列NSCoding

    UITableView:CVarArgEqu可转换可散列NSCoding

    UIImage:CVarArgEqu可转换可散列NSCoding

    UIPickerView:CVarArgEqu可转换可散列NSCoding

    UIView:CVarArgEqu可转换可散列NSCoding

    UIImageView:CVarArgEqu可转换可散列NSCoding

    UINavigationBar:CVarArgEquableHasableNSCoding

    UIButton:CVarArgEqu可转换可散列NSCoding

    UIBarButtonItem:CVarArgEqu可转换可散列NSCoding

    UIStackView:CVarArgEqu可转换可散列NSCoding

    UIToolbar:CVarArgEqu可转换可散列NSCoding

    UITabBar:CVarArgEqu可转换可散列NSCoding

    UITabBarItem:CVarArgEqu可转换可散列NSCoding

    UIScrollView:CVarArgEqu可转换可散列NSCoding

    UISplitViewController:CVarArgEquableHasableNSCoding

    UIViewController:CVarArgEquableHasableNSCoding

    UIScreen:CVarArg

    用户界面:CVarArg可均衡可散列NSCoding

    UISlider:CVarArgEquableHasableNSCoding

    UIAlertAction:CVarArg

    UIAlertController:CVarArgEquableHasableNSCoding

    UIImageAsset:CVarArgEqu可转换可散列NSCoding

    UIDatePicker:CVarArgEquableHasableNSCoding

    UINib:CVarArg

    用户响应器:CVarArg

    UIWindow:CVarArgEquable可散列NSCoding

    UIRegion:CVarArgEqu可转换可散列NSCoding

    UIControl:CVarArgEqu可转换可散列NSCoding

    UIBezierPath:CVarArgEquableHasableNSCoding

    UIVisualEffect:CVarArgEqu可转换可散列NSCoding

    UISearchBar:CVarArgEquableHasableNSCoding

    UIMenuItem:CVarArg

    UIMenuController:CVarArg

    UIStoryboard:CVarArg

    还有更多…



    无论如何,我希望这一切都能帮助您解决问题,如果您有任何问题,建议等,请随时提问!