【问题标题】:UIView isKindOfClass in Swift 3Swift 3 中的 UIView isKindOfClass
【发布时间】:2025-12-08 17:10:01
【问题描述】:

所以我有这个代码:

if view.isKindOfClass(classType){...}

这在 Swift 2 中运行良好,但现在我在 Swift 3 中,我收到此错误:

UIView 类型的值没有成员 isKindOfClass

如何在 Swift 3 中进行测试?

【问题讨论】:

标签: swift uiview swift3


【解决方案1】:

只需使用is 运算符进行检查

if view is UITableViewCell { 
  //do something
}

guard view is UITableViewCell else {
  return
}
//do something

如果您需要将视图用​​作类类型的实例,请使用as 运算符进行强制转换:

if let view = view as? UITableViewCell {
  //here view is a UITableViewCell
}

guard let view = view as? UITableViewCell else {
  return
}
//here view is a UITableViewCell

【讨论】:

    【解决方案2】:

    您可以使用isKind(of:),但最好使用更快捷的isas

    看一个愚蠢的例子:

    import Foundation
    
    class Base {}
    class SuperX: Base {}
    class X: SuperX {}
    class Y {}
    
    func f(p: Any) {
        print("p: \(p)")
        guard let x = p as? Base
            else { return print("    Unacceptable") }
    
        if x is X {
            print("    X")
        }
        if x is SuperX {
            print("    Super X")
        }
        else {
            print("    Not X")
        }
    }
    
    f(p: Base())
    f(p: SuperX())
    f(p: X())
    f(p: "hey")
    f(p: Y())
    f(p: 7)
    

    在操场上运行代码,输出将是:

    p: Base
        Not X
    p: SuperX
        Super X
    p: X
        X
        Super X
    p: hey
        Unacceptable
    p: Y
        Unacceptable
    p: 7
        Unacceptable
    

    【讨论】:

      【解决方案3】:

      您可以在 Swift 3 中尝试使用这三个选项:

      选项1:

      if view is UITabBarItem {
      
      }
      

      选项 2:

      if view.isKind(of:UITabBarItem.self) {
      
      }
      

      选项 3:

      if view.isMember(of:UITabBarItem.self) {
      
      }
      

      isKind:of 和 isMember:of 的区别是:

      • isKind:of 如果接收者是确切类的实例,或者如果接收者是该类的任何子类的实例,则返回 YES。
      • isMember:of only 如果接收者是您要检查的确切类的实例,则返回 YES

      【讨论】: