Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

ios - UITableView with Multiple Sections using Realm and Swift

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.

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"
    }
}

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.

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
}

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

Thank you for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
}

Which looks like this:

screenshot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...