2015-11-02 18 views
6

性能試圖獲得的UIView或UIViewController中的所有屬性與follownig:斯威夫特鏡面反射沒有返回上的UIView

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的似乎並沒有返回的屬性,有什麼建議?

回答

5

不知道你想什麼來實現,但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", "hash", "superclass", "description", "debugDescription", "hash", "superclass", "description", "debugDescription", "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", "unsatisfiableConstraintsLoggingSuspended", "_shouldArchiveUIAppearanceTags", "_interactionTintColor", "_backdropMaskViewForGrayscaleTint", "_backdropMaskViewForColorTint", "_backdropMaskViewForFilters", "_backdropMaskViews", "_wantsGeometryChangeNotification", "contentSizeNotificationToken", "layoutMarginsGuide", "readableContentGuide", "hash", "superclass", "description", "debugDescription", "traitCollection", "preferredFocusedView", "center", "bounds", "transform", "collisionBoundsType", "collisionBoundingPath"]\n" 

此外,我看到一些怪異的應用你的代碼到UIKit對象。不確定導致它失敗的變量是什麼。它似乎寫在斯威夫特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", "name", "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" 

因此,無論這是一個錯誤或存在一定的侷限性在斯威夫特< - > ObjC在斯威夫特的當前版本。也許這與@ user3441734在他的回答中指出的有關。

順便說一句,所有的代碼都是在操作系統的最新版本的Xcode(7.1.1)上運行的。

+0

感謝您的好評!這個問題就像你傷心只能在NSObject繼承上一樣,我一直在尋找一些通用的女巫可以在任何情況下工作。加上(我對此並不是100%肯定),這種方式似乎有點「沉重」,以迅捷的方式獲得了成功。我接受你的答案,因爲它是最好的答案。再次感謝。 – MCMatan

4
import UIKit 

let viewController = UIViewController() 
let view = UIView() 
class MyViewController: UIViewController { 
    let i = 1 
    let myView = MyView() 
} 
class MyView : UIView { 
    let label = UILabel() 
    let i = 1 
} 

Mirror(reflecting: MyViewController()).children.count // 2 
Mirror(reflecting: MyView()).children.count    // 0 

你是對的!只需填寫錯誤報告...

,或者是破壞,因爲我發現這個

extension UIView : _Reflectable { 
} 
+0

這當然是「破壞」,我同意。 –