【问题标题】:Creating an indexed tableview using Realm in swift在 swift 中使用 Realm 创建索引表视图
【发布时间】:2016-10-13 18:43:45
【问题描述】:

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

我的代码如下所示:

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

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

编辑

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

TableViewController 代码:

var contacts: Results<ContactItem>!

var contactIndexTitles = String

类 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。我似乎无法使代码正确,以便能够转到正确部分的正确行。 如何从正确的部分中选择正确的行?

【问题讨论】:

  • 查看 stackoverflow.com/a/38797693/373262 以获取分组表视图的示例。
  • 我一直在查看建议的示例,并且可以看到它是如何使用硬编码信息完成的,但不使用该部分的数组和对象的结果列表。要么是我遗漏了一些简单的东西,要么是我偏离了标准,而不是程序员,可能是后者。

标签: ios swift uitableview realm


【解决方案1】:

这是一个来自 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
    }
}

这是最终结果:

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

【讨论】:

  • 感谢您的回答。但它并没有达到我的预期。模拟器上唯一显示的是“A”。抱歉,不知道如何在此评论中添加屏幕截图。
  • 我添加了这段代码生成的截图,以及完整 Xcode 项目的链接。
  • 我已经看过这个项目了,谢谢。我无法在不进行更改的情况下运行它。我正在使用 xcode 7.3 swift 2.2。修改几个位以便能够运行仅在模拟器上生成“A”的代码。再次感谢您的帮助和耐心。
  • 是的,我有点猜到它出现的错误。我仍在尝试对其进行排序。估计会是一个漫长的学习过程。还有什么想法吗?
  • 为什么是一个漫长的学习过程? Xcode 可以在 Mac App Store 上找到,这个项目是完全独立的。
猜你喜欢
  • 1970-01-01
  • 2011-02-15
  • 2019-08-05
  • 2022-01-17
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
相关资源
最近更新 更多