我按字母顺序排列了我的Realm数据。
但是我想在我的表视图中显示它,就像内置iPhone应用程序中的联系人列表一样,从A到Z有不同的部分。
我应该做什么?
MainViewController:
class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var contact_tableview: UITableView!
let realm = try! Realm()
var ContactList: Results<ContactObjectss> {
get {
// return realm.objects(ContactObjectss.self)
return realm.objects(ContactObjectss.self).sorted(byKeyPath: "first_name", ascending: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "IRANSansWeb-Medium", size: 17)!]
contact_tableview.delegate = self
contact_tableview.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ContactList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell") as! ContactCell
let item = ContactList[indexPath.row]
cell.lblName!.text = item.first_name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let ContactV = storyboard?.instantiateViewController(withIdentifier: "ViewContact") as! ContactInfoVC
navigationController?.pushViewController(ContactV, animated: true)
ContactV.ContactID = ContactList[indexPath.row]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
contact_tableview.reloadData()
// to reload selected cell
}
}
ContactObjectss:
class ContactObjectss : Object {
dynamic var id:Int = 0
dynamic var first_name = ""
dynamic var last_name = ""
dynamic var work_email = ""
dynamic var personal_email = ""
dynamic var contact_picture = ""
dynamic var mobile_number = ""
dynamic var home_number = ""
dynamic var isFavorite = false
dynamic var Notes = ""
dynamic var picture : NSData?
}
答案 0 :(得分:0)
我认为您可以通过制作26个部分(每个字母表中的一个字母)来完成此操作,然后计算每个部分ContactObjects
的数量。
func numberOfSections(in tableView: UITableView) -> Int {
return 26 // letters of the alphabet
}
我假设您的ContactObjects根据其名字按字母顺序排序,如果它们不仅仅用first_name
替换last_name
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionLetter = "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".components(separatedBy: ",")[section-1]
let contactsWithLetter = ContactList.filter {String($0.first_name.lowercased()[$0.first_name.startIndex]) == sectionLetter} //had to use the startIndex thing because apparently $0.first_name is an inout property and therefore you can't just get it's characters
return contactsWithLetter.count
}