使用Realm和Swift的多个部分的UITableView [英] UITableView with Multiple Sections using Realm and Swift

查看:92
本文介绍了使用Realm和Swift的多个部分的UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我发现了很多关于UITableView和多个部分的信息,但是,它们总是包含字符串,数组,静态数据,Obj-C或其他我无法转换到我的情况的东西,主要是因为我是开发应用程序的新手。任何帮助都非常感谢,因为我已经用了一个多月的时间尝试了不同的方法而没有成功。

Ok, so I found a lot of information regarding UITableView and multiple sections, however, they are always with strings, arrays, static data, Obj-C or something else with which I am unable to translate to my situation, mainly because I am completely new to developing apps. Any help is greatly appreciated since it has been a little over a month that I have been trying different approaches without success.

所以我有多个具有以下属性的Dog对象:

So I have multiple Dog objects with the following properties:

class Dog: Object {
    dynamic var name = ""
    dynamic var race = ""
    dynamic var age = 0
    dynamic var owner = ""
    dynamic var dogID = ""

    override static func primaryKey() -> String? {
        return "dogID"
    }
}

我的ViewController文件我有以下代码(我删除了不相关的行):

And in my ViewController file I have the following code (I removed the irrelevant lines):

let realm = try! Realm()
var dogResults : Results<Dog>?

override func viewDidLoad() {
    super.viewDidLoad()

    self.dogResults = realm.objects(Dog.self)

}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    let dog = self.dogResults![indexPath.row]
    cell.textLabel?.text = dog.name
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        // ?
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // ?
}

我想通过狗的种族财产来组织这些部分对象,但是我很难实现这个目标。

I would like to organize the sections by the "race" property from the Dog object, however I am having a very difficult time achieving this.

我看到了几个例子,他们使用了if语句的部分,我试过了然而,我想要在其他一些例子中看到的更清洁的方法,使用:

I saw a few examples where they use the "if" statement for the sections, I have tried that and was not able to get the proper results, however, I would like the cleaner approach I have seen in some other examples, using:

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

我做了各种尝试,但作为一个Realm DB和swift我在大多数示例后都遇到了问题。

I have made various attempts, but being a Realm DB and swift I am having problems following most of the examples.

感谢您的时间。

推荐答案

这里有一些示例代码可以完全满足您的需求:

Here's some sample code that does exactly what you're looking for:

import UIKit
import RealmSwift

class Dog: Object {
    dynamic var name = ""
    dynamic var race = ""
    dynamic var age = 0
    dynamic var owner = ""
    dynamic var dogID = ""

    override static func primaryKey() -> String? {
        return "dogID"
    }

    convenience init(name: String, race: String, dogID: String) {
        self.init()
        self.name = name
        self.race = race
        self.dogID = dogID
    }
}

class TableViewController: UITableViewController {
    let items = try! Realm().objects(Dog.self).sorted(["race", "name"])
    var sectionNames: [String] {
        return Set(items.valueForKeyPath("race") as! [String]).sort()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        let realm = try! Realm()
        if realm.isEmpty {
            try! realm.write {
                realm.add(Dog(name: "Bailey", race: "Golden Retrievers", dogID: "0"))
                realm.add(Dog(name: "Bella", race: "German Shepherds", dogID: "1"))
                realm.add(Dog(name: "Max", race: "Bulldogs", dogID: "2"))
                realm.add(Dog(name: "Lucy", race: "Yorkshire Terriers", dogID: "3"))
                realm.add(Dog(name: "Charlie", race: "Bulldogs", dogID: "4"))
                realm.add(Dog(name: "Molly", race: "German Shepherds", dogID: "5"))
                realm.add(Dog(name: "Buddy", race: "German Shepherds", dogID: "6"))
                realm.add(Dog(name: "Daisy", race: "Siberian Huskies", dogID: "7"))
            }
        }
    }

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

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionNames[section]
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return items.filter("race == %@", sectionNames[section]).count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        cell.textLabel?.text = items.filter("race == %@", sectionNames[indexPath.section])[indexPath.row].name
        return cell
    }
}

看起来像这样:

这篇关于使用Realm和Swift的多个部分的UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆