在swift中使用Realm创建索引表视图

时间:2016-10-13 18:43:46

标签: ios swift uitableview realm

我有一个存储在领域数据库中的联系人列表,现在我想在表格视图中显示联系人的姓名。作为列表,这工作正常,可以按名称的升序排序。我正在努力为索引列表中的每个字母分组这些名称。我的代码用相同的信息填充每个部分。

我的代码如下所示:

    var contacts: Results<ContactItem>!
var contactIndexTitles = [String]()

@IBOutlet weak var tblContacts: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.setupUI()
    let contactIndex = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
    contactIndexTitles = contactIndex.componentsSeparatedByString(" ")
    self.reloadTheTable()
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    reloadTheTable()
}


func setupUI() {
    tblContacts.delegate = self
    tblContacts.dataSource = self
}

func reloadTheTable() {
    do {
        let realm = try Realm()
        contacts = realm.objects(ContactItem).sorted("Name", ascending: true)
        tblContacts.reloadData()
        print("reload tbl \(contacts)")

    } catch {

    }
}

//willDisplayCell forRowAtIndexPath
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}

//numberOfSectionsInTableView
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return contactIndexTitles.count
}

//sectionForSectionIndexTitle
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int{

    return index
}

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

    return self.contactIndexTitles[section] as String
}

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

//sectionIndexTitlesForTableView
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return contactIndexTitles as [String]
}

//cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let identifer: String = "myCell"
    var cell = tblContacts.dequeueReusableCellWithIdentifier(identifer)

    if cell == nil {
        cell = UITableViewCell(style: .Subtitle, reuseIdentifier: identifer)
    }

    let contactinfo = contacts[indexPath.row]
    cell?.textLabel?.text = contactinfo.Name
    cell?.detailTextLabel?.text = contactinfo.KeyNumber
    return cell!
}

Screenshot

有关如何过滤领域数据库并正确填充这些部分的任何建议吗?

修改

所以我使用第一个链接和给出的样本修改了代码,它显示正常。

current screenshot

TableViewController代码:

var contacts: Results<ContactItem>!

var contactIndexTitles = String

class TableViewController:UITableViewController {

@IBOutlet weak var tblcontacts: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    self.setupUI()
    self.reloadTheTable()
    let contactIndex = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
    contactIndexTitles = contactIndex.componentsSeparatedByString(" ")

    //print(Realm.Configuration.defaultConfiguration.fileURL!)
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    reloadTheTable()
}

func setupUI() {

    tblcontacts.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

func reloadTheTable() {
    do {
        let realm = try Realm()
        contacts = realm.objects(ContactItem.self).sorted("Name")
        tblcontacts.reloadData()
    }
    catch
    {

    }
}

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

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

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return contactIndexTitles
}

override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
    return contacts.filter("Name BEGINSWITH %@", contactIndexTitles[section]).count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tblcontacts.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    cell.textLabel?.text = contacts.filter("Name BEGINSWITH %@", contactIndexTitles[indexPath.section])[indexPath.row].Name
    return cell

}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    let contact : ContactItem = contacts[indexPath.row]  //, contactIndexTitles[indexPath.section])
    print(contact)
    performSegueWithIdentifier("addContact", sender: contact)
    print("Selected row at \(indexPath.row)")
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if(segue.identifier == "addContact")
    {
        let viewController = segue.destinationViewController as! AddEntryViewController
        viewController.contact = sender as! ContactItem

    }
}

}

现在我还有一个问题,那就是下一个控制器的segue。我似乎无法使代码正确,以便能够在正确的部分中找到正确的行。 如何从正确的部分中选择正确的行?

1 个答案:

答案 0 :(得分:4)

以下是为您的模型从https://stackoverflow.com/a/38797693/373262派生的示例,并指定了一个硬编码的剖面标题数组作为您上述请求的评论:

import UIKit
import RealmSwift

class ContactItem: Object {
    dynamic var name = ""
    dynamic var keyNumber = ""

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

let alphabet = (UnicodeScalar("A").value...UnicodeScalar("Z").value).flatMap(UnicodeScalar.init)

class ViewController: UITableViewController {
    let items = try! Realm().objects(ContactItem.self).sorted(byProperty: "name")

    override func viewDidLoad() {
        super.viewDidLoad()

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

        let realm = try! Realm()
        if realm.isEmpty {
            try! realm.write {
                realm.add(ContactItem(name: "Bailey", keyNumber: "0"))
                realm.add(ContactItem(name: "Bella", keyNumber: "1"))
                realm.add(ContactItem(name: "Max", keyNumber:"2"))
                realm.add(ContactItem(name: "Lucy", keyNumber: "3"))
                realm.add(ContactItem(name: "Charlie", keyNumber:"4"))
                realm.add(ContactItem(name: "Molly", keyNumber: "5"))
                realm.add(ContactItem(name: "Buddy", keyNumber: "6"))
                realm.add(ContactItem(name: "Daisy", keyNumber: "7"))
            }
        }
    }

    func items(forSection section: Int) -> Results<ContactItem> {
        return items.filter("name BEGINSWITH %@", alphabet[section].description)
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return alphabet.count
    }

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

    override func tableView(_ tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return items(forSection: section).count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let contactinfo = items(forSection: indexPath.section)[indexPath.row]
        cell.textLabel?.text = contactinfo.name
        cell.detailTextLabel?.text = contactinfo.keyNumber
        return cell
    }
}

这是最终结果:

screenshot

Xcode项目的链接:https://static.realm.io/debug/RealmContacts.tgz