使用 .plist 中的数据加载 UIViewController

Load a UIViewController with data from .plist

我在情节提要中设置了一个 UITableView,静态行填充了不同的内容,并且所有内容都转到一个 UIViewController。对于我打算加载的每个视图(包含不同的内容),我也有一个单独的 plist,我想根据选择的行加载它。

作为奖励,我宁愿有一个 plist,UITableViewController 将用它来填充行(而不是在故事板中有 120 多个静态行),但我也不确定该怎么做.

我搜索了很多,但只找到了 Objective-C 的东西。我对 Swift 有点陌生,从来没有深入了解 Objective-C,但我认为我已经掌握了基础知识。

好的,我的问题。我的问题是,如何加载每个单独的 plist(每行一个)并在显示 UIViewController 时显示其内容? 我的额外问题是:我如何将我的 120 多个静态行合并到一个 plist 中,该 plist 基本上完成了同样的事情,除了不是编辑 SB 来添加新行,我只需要添加到 plist?

首先,很少用plist来存储这样的内容。不易维护。使用XML 或json 来存储它是更好的选择。

关于您的问题 #1,

将下面的代码放入一个循环中,以将你的 plist 加载到一个字典中,如下所示:

let path = NSBundle.mainBundle().pathForResource("Your_path", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)

您可能想将所有的字典存储到一个数组中,这样您就知道您有多少个 plist。假设我们在您的视图控制器中有 dictArray 属性 来保存您所有的指令。

您没有在 SB 上为 UITableView 添加静态单元格,效率不高。您只需让 dataSource 委托加载数据并根据需要创建尽可能多的单元格。

我会留下一些代码给你写,这会让你暖和起来。我只给出代码的重要部分。

不要忘记设置数据源并委托给适当的对象,例如 self!

然后,

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dictArray.count
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell

    let row = indexPath.row
    let dictOfPlist = self.dictArray[row]

    // now you get your plist while configuring your cells,
    // do your customization for your cells from now on

    return cell
}

// MARK:  UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let row = indexPath.row
    let dictOfPlist = self.dictArray[row]

    // if you tap one cell, now you get its corresponding plist
    // time to pass the data to your view controller
    // either use segue or other ways to do it
    }
}

将数据传递到新的 UIViewController 的一些方法:

如果你在故事板中存在 segue,并且在你的 2 个视图之间有一个 segue 标识符,你可以使用以下方式以编程方式调用它:

performSegueWithIdentifier("mySegueID", sender: yourDataDict)

稍后您可以在 nextViewController 中访问您的 DataDict 以加载它

你也可以这样做:

nextViewController.dataDict = yourDataDict // set a public property so you can access it later on

presentViewController(nextViewController, animated: true, completion: nil)

或者如果您在导航控制器中:

self.navigationController?.pushViewController(nextViewController, animated: true)

要将你的plist合并为一个plist,你可能需要写一些小程序或脚本来合并它们;或复制它们。有很多方法可以做到这一点。但正如我所建议的,我不建议你继续使用 plist 来做这样的事情。你最好一开始就换成另一种形式。否则当你意识到你真的需要改变时,为时已晚,你有很多代码要重写。