2016-08-25 28 views
0

我正在构建一个应用程序,在UITableView中有几个部分。我目前的解决方案是在字典中收集我的数据,然后为每个部分选择一个键。有更好的解决方案吗?在UITableView的部分中填充行的最佳方法是什么?

+0

1)段号=字典中没有键2)段号中的行数=段号中字典中没有值的值 – pkc456

+0

确切地说,是这样做的吗? – Recusiwe

+0

是的,这是正确的方法。我还应该分享代码吗? – pkc456

回答

0

这里是我写的一个快速例子。请注意,它很容易出错,因为它不检查密钥是否存在,也不会创建合适的单元格。

你也可以用字典来做到这一点,因为你可以迭代它的内容。

希望它能帮助:

class AwesomeTable: UITableViewController { 

    private var tableContent: [[String]] = [["Section 1, row 1", "Section 1, row 2"], ["Section 2, row 1", "Section 2, row 2"]] 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return tableContent.count 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return tableContent[section].count 
    } 

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

     let item = tableContent[indexPath.section][indexPath.row] 

     cell.textLabel?.text = item 

     return cell 
    } 

} 
+0

这不是一个很好的做法。 1)。大规模地维护该词典的内容是非常困难的。 2)。对大字典进行排序或排序几乎是不可能的。 3)。 4)创建非常复杂的单元非常困难。如果您的单元格类型超过1个或2个,那么它会变得乱糟糟,因为您的cellForRowAtIndexPath 513)。没有明确设置。你只会传递正确的字典内容,这是不好的。 –

+0

我同意,但考虑到它回答它的问题。有很多方法可以更好地做到这一点,其中一个就是你给出的答案。在你的回答中,代码更清晰,更易于阅读,但我想争辩说,复杂性仍然大致相同。 –

2

其中一个很好的办法吧 - 直销模式的映射,尤其是与迅速枚举良好。例如,你有2个不同的部分,3种不同类型的行。您的enum和ViewController代码如下所示:

enum TableViewSectionTypes { 
    case SectionOne 
    case SectionTwo 
} 

enum TableViewRowTypes { 
    case RawTypeOne 
    case RawTypeTwo 
    case RawTypeThreeWithAssociatedModel(ModelForRowTypeNumberThree) 
} 

struct ModelForRowTypeNumberThree { 
    let paramOne: String 
    let paramTwo: UIImage 
    let paramThree: String 
    let paramFour: NSData 
} 

struct TableViewSection { 
    let type: TableViewSectionTypes 
    let raws: [TableViewRowTypes] 
} 

class ViewController: UIViewController, UITableViewDataSource { 

    var sections = [TableViewSection]() 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return sections[section].raws.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let raw = sections[indexPath.section].raws[indexPath.row] 
     switch raw { 
     case .RawTypeOne: 
      // Here return cell of first type 
     case .RawTypeTwo: 
      // There return cell of second type 
     case .RawTypeThreeWithAssociatedModel(let modelForRawTypeThree): 
      // And finally here you can use your model and bind it to your cell and return it 
     } 
    } 
} 

有什么好处?强大的典型化,明确的建模和显式处理您的各种细胞类型。在这种情况下你必须做的唯一简单的事情就是将你的数据解析成这个枚举和结构,以及你为你的字典做的。

+0

这似乎很有希望解决我的问题。不过,我无法弄清楚如何将我的Firebase数据库中的数据解析到枚举中。我可以直接将数据从数据库加载到枚举中吗?或者我在哪里执行此步骤? 我已经有一个像我的ModelForRowTypeNumberThree结构。 在我的应用程序中,所有的行类型都是相同的,但是由4个不同的NSDictionarys填充。这可能吗? – AlexVilla147

相关问题