Swift:以编程方式枚举来自UIVIewController

时间:2016-01-28 11:25:21

标签: swift uistoryboardsegue

我想列出来自UIViewController的传出segue,如Programmatically enumerate outgoing Segues for a UIViewController中所述,但在Swift中。 (Swift 2,Xcode 7,iOS8 +)。

我能做到

override func viewDidLoad() {
    super.viewDidLoad()
    let s = valueForKey("storyboardSegueTemplates")
    print("switchingVC: segues: \(s)") 
}

并产生类似

的输出
switchingVC: segues: Optional((
    "<UIStoryboardPresentationSegueTemplate: 0x1754a130>",
    "<UIStoryboardPresentationSegueTemplate: 0x17534f60>",
    "<UIStoryboardPresentationSegueTemplate: 0x17534fc0>"
))

但在那之后我很难生产任何东西。我找不到UIStoryboardPresentationSegueTemplate的任何定义。我怎么能说服斯威夫特告诉我里面有什么?如何找到segue identifier

谢谢!

2 个答案:

答案 0 :(得分:2)

valueForKey("storyboardSegueTemplates") UNDOCUMENTED 属性,UIStoryboardPresentationSegueTemplate UNDOCUMENTED 类。如果您要将应用程序上传到App Store,请注意拒绝App Store。

如果您想在内部项目中使用此功能,请使用以下

for template in (valueForKey("storyboardSegueTemplates") as? [AnyObject])! {
    if let identifier = template.valueForKey("identifier") as? String {
        print("identifier - " + identifier)
    }
    else {
        print("no identifier for \(template)")
    }
}

https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UIStoryboardSegueTemplate.h

找到

答案 1 :(得分:0)

根据Swift 4.2和https://stackoverflow.com/a/35060917/1058199版本。谢谢/ johnykutty。

import UIKit

extension UIViewController {

     // Segue aids in Swift
     @objc func isValidSegue(_ segueId: String?) -> Bool {
        let filteredArray = (value(forKey: "storyboardSegueTemplates") as? NSArray)?.filtered(using: NSPredicate(format: "identifier = %@", segueId ?? ""))
        let isValid = (filteredArray?.count ?? 0) > 0
        return isValid
     }

     @objc func segues() -> Array<Any>? {
        let segues = self.value(forKey: "storyboardSegueTemplates")
        return segues as! Array<Any>?
     }

    @objc func segueNames() -> Array<AnyHashable> {
        var segueNames = Array<Any>()

        let filteredArray = (value(forKey: "storyboardSegueTemplates") as? NSArray)?.filtered(using: NSPredicate(format: "identifier != nil" ))

        for template in filteredArray! as [AnyObject] {
           if let identifier = (template.value(forKey: "identifier") as? String) {
               segueNames.append(identifier)
            }
            else {
                segueNames.append("no identifier for \(template)")
            }
        }

        return segueNames as! Array<AnyHashable>
    }
}

我知道我对谓词的使用可能会更好,但是Swift在处理迭代数组时就是这样的PITA。请随时进行改进。