加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift Mirror反射不返回UIVIew上的属性

发布时间:2020-12-14 05:38:34 所属栏目:百科 来源:网络整理
导读:尝试使用follownig获取UIView或UIViewController的所有属性: func propertysNames()-[String]{ var s = [String]() for c in Mirror(reflecting: self).children { if let name = c.label{ s.append(name) } } return s} 这适用于UIVIewController,但UIView
尝试使用follownig获取UIView或UIViewController的所有属性:
func propertysNames()->[String]{
    var s = [String]()
    for c in Mirror(reflecting: self).children
    {
        if let name = c.label{
            s.append(name)
        }
    }
    return s
}

这适用于UIVIewController,但UIView似乎没有返回属性,任何建议?

不知道你想要实现什么,但UIView继承了NSObject.因此,您可以使用大量的objc运行时.因此,作为替代方案,您可以执行以下操作:
import UIKit

extension NSObject {
  func propertysNames() -> [String]{
    var count : UInt32 = 0
    let classToInspect = self.dynamicType
    let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect,&count)
    var propertyNames : [String] = []
    let intCount = Int(count)
    for var i = 0; i < intCount; i++ {
      let property : objc_property_t = properties[i]
      let propertyName = NSString(UTF8String: property_getName(property))!
      propertyNames.append(propertyName as String)
    }
    free(properties)
    return propertyNames
  }
}

print(UIView().propertysNames())
// prints: "["_mayRemainFocused","_sensitivitySize","skipsSubviewEnumeration","viewTraversalMark","viewDelegate","monitorsSubtree","backgroundColorSystemColorName","currentScreenScale","maskView","_userInterfaceIdiom","hash","superclass","description","debugDescription","gesturesEnabled","deliversTouchesForGesturesToSuperview","deliversButtonsForGesturesToSuperview","_shouldReverseLayoutDirection","leadingAnchor","trailingAnchor","leftAnchor","rightAnchor","topAnchor","bottomAnchor","widthAnchor","heightAnchor","centerXAnchor","centerYAnchor","firstBaselineAnchor","lastBaselineAnchor","_keyboardOrientation","_touchForceObservable","_inheritedRenderConfig","_lightStyleRenderConfig","_accessoryViewFrame","unsatisfiableConstraintsLoggingSuspended","userInteractionEnabled","tag","layer","focused","semanticContentAttribute","interactionTintColor","_layoutDebuggingIdentifier","_countOfMotionEffectsInSubtree","_maskView","_ancestorDefinesTintColor","_ancestorDefinesTintAdjustmentMode","_presentationControllerToNotifyOnLayoutSubviews","_rawLayoutMargins","_inferredLayoutMargins","_dontUpdateInferredLayoutMargins","_tracksFocusedAncestors","_countOfFocusedAncestorTrackingViewsInSubtree","_mutableLayoutGuides","_mutableLayoutArrangements","_hiddenManagedByLayoutArrangementCount","_pendingHiddenCount","previewingSegueTemplateStorage","_continuousCornerRadius","_canBeParentTraitEnviroment","_layoutEngine","_boundsWidthVariable","_boundsHeightVariable","_minXVariable","_minYVariable","_internalConstraints","_constraintsExceptingSubviewAutoresizingConstraints","_shouldArchiveUIAppearanceTags","_interactionTintColor","_backdropMaskViewForGrayscaleTint","_backdropMaskViewForColorTint","_backdropMaskViewForFilters","_backdropMaskViews","_wantsGeometryChangeNotification","contentSizeNotificationToken","layoutMarginsGuide","readableContentGuide","traitCollection","preferredFocusedView","center","bounds","transform","collisionBoundsType","collisionBoundingPath"]n"

此外,我确实看到一些将您的代码应用于UIKit对象的奇怪之处.不确定导致失败的变量是什么.它似乎在用Swift编写的NSObject类型上工作正常:

import UIKit

class Fruit {
  var type=1
  var name="Apple"
  var delicious=true
}

var s = [String]()
for c in Mirror(reflecting: Fruit()).children
{
  if let name = c.label{
    s.append(name)
  }
}

print(s)
// works: "["type","name","delicious"]n"

class FruitNSObject: NSObject {
  var type:NSNumber=1
  var name:NSString="Apple"
  var delicious=true
}

s = [String]()
for c in Mirror(reflecting: FruitNSObject()).children
{
  if let name = c.label {
    s.append(name)
  }
}

print(s)
// works: "["type","delicious"]n"

s = [String]()
for c in Mirror(reflecting: UIView()).children
{
  if let name = c.label {
    s.append(name)
  }
}

print(s)
// doesn't work: "[]n"

s = [String]()
for c in Mirror(reflecting: UIViewController()).children
{
  if let name = c.label {
    s.append(name)
  }
}

print(s)
// doesn't work: "[]n"

所以要么这是一个bug,要么在Swift< - >中有一些限制. ObjC在当前版本的Swift中.也许这与@ user3441734在他的回答中指出的有关.

顺便说一句,所有代码都是在操场上最新版本的Xcode(即7.1.1)上运行的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读