2016-10-13 15 views
2

レルムデータベースに格納されている連絡先のリストがあり、今では連絡先の名前をテーブルビューに表示します。リストとしてはうまく動作し、名前の昇順でソートすることができます。私は、インデックスリストの各文字のためにこれらの名前をグループ化するのに苦労しています。私のコードは、各セクションに同じ情報を埋めています。すぐに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

任意の提案ですか?

EDITは、だから私は、最初のリンクと、与えられたサンプルを使用してコードを修正したのだが、[OK]を表示しています。

current screenshot

TableViewControllerコード:

var contacts: Results<ContactItem>! 

するvar contactIndexTitles =ストリング

クラス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 

    } 
} 

}

もう1つ問題があり、次のコントローラにセグがあります。私は正しいセクションに正しい行に行くことができるように正しいコードを取得するように見えることはできません。 正しいセクションから正しい行を選択するにはどうすればよいですか?ここで

+0

例については、http://stackoverflow.com/a/38797693/373262を参照してください。グループ化されたテーブルビュー。 – jpsim

+0

私は提案された例を見てきましたが、ハードコーディングされた情報を使って、そのセクションの配列とオブジェクトの結果リストを使用していないことを確認できます。どちらかというとシンプルなものが欠けているか、私はマークから離れていて、おそらくプログラマーではないでしょう。 – scooby

答えて

4

は、あなたのモデルのためにhttps://stackoverflow.com/a/38797693/373262由来のサンプルと要求された上記のあなたのコメントとして、セクションタイトルのハードコードされた配列を指定します:

screenshot

と、A:

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

+0

答えをありがとう。それは私が思ったことをしなかった。シミュレータに表示されるのは「A」だけでした。このコメントにスクリーンショットを追加する方法がわかりません。 – scooby

+0

このコードが生成するもののスクリーンショットと、完全なXcodeプロジェクトへのリンクを追加しました。 – jpsim

+0

私はプロジェクトを見てきましたありがとうございます。私はそれを変更せずに実行することはできません。私はxcode 7.3 swift 2.2を使用しています。コードを実行できるようにカップルビットを変更すると、シミュレータ上でのみ "A"が生成されます。あなたの助けと忍耐をもう一度ありがとう。 – scooby

関連する問題