Contact
import UIKitclass Contact: NSObject {? ??
? ? var name:String!??
? var gender:String!??
? var phone:String!? ?
?? ? override init() {? ? ??
? ? ? }?
?? init(dict:Dictionary) {
self.name = dict["name"]
self.gender = dict["gender"]
self.phone = dict["phone"]
}
}
ContactListViewController
import UIKit
class ContactListViewController: UITableViewController {
//定義重用標識
let girlCell = "girlCell"
let boyCell = "boyCell"
//定義字典,作為數據源
var contactSource:[String:[Contact]] = Dictionary()
//存放排好序的key值
var keysArray:[String] = Array()
override func viewDidLoad() {
super.viewDidLoad()
//調用制造數據源方法
self.creatData()
//注冊cell
self.tableView.register(GirlStudentCell.self, forCellReuseIdentifier: girlCell)
self.tableView.register(BoyStudentCell.self, forCellReuseIdentifier: boyCell)
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
//創造數據的方法
func creatData(){
let dic =? [
"W":[
["name":"王哲磊","gender":"男","phone":"13525704818"],
["name":"王浩","gender":"男","phone":"13525704817"],
["name":"王曉紅","gender":"女","phone":"13525704828"],
["name":"王琳","gender":"女","phone":"13525704898"]
],
"C":[
["name":"陳楊","gender":"女","phone":"13525704898"],
["name":"陳芮","gender":"女","phone":"13525704857"]
],
"B":[
["name":"邊文達","gender":"男","phone":"13525724818"],
["name":"寶音","gender":"女","phone":"13525704217"],
["name":"白婧","gender":"女","phone":"13529704828"]
],
"L":[
["name":"李玲","gender":"女","phone":"13725704818"],
["name":"劉二蛋","gender":"男","phone":"13529704817"],
["name":"劉婧","gender":"女","phone":"13525714828"],
["name":"劉福宏","gender":"女","phone":"13525794898"]
]
]
//從dict數據源中把數據讀入到contactSource中
for key in dic.keys{
//取出數組對象
let array = dic[key]
//創建數組存儲聯系人對象
var group:[Contact] = Array()
for dictionary in array!{
//使用字典初始化聯系人對象
let aContact = Contact(dict: dictionary)
//將聯系人對象添加到數組
group.append(aContact)
}
//使用數據源存儲數據
contactSource[key] = group
}
//print(contactSource)
//將字典中的key值排序
let keys = contactSource.keys
//對字典中的key值排序
keysArray = keys.sorted()
// print(keysArray)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
//等于鍵值對的個數
return contactSource.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//根據分區下標找到對應的key值
let key = keysArray[section]
//根據key值找到分組
let group = contactSource[key]
//分組中元素的個數就是分區中cell的個數
return (group?.count)!
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let key = keysArray[indexPath.section]
let group = contactSource[key]
//根據cell的下標取出數組對應位置數據模型聯系人
let aContact = group?[indexPath.row]
if aContact?.gender == "男"{
let cell = tableView.dequeueReusableCell(withIdentifier: boyCell) as! BoyStudentCell
//調用給cell賦值的方法
cell.setValueViews(aContact: aContact!)
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: girlCell) as! GirlStudentCell
cell.setValueByContact(contact: aContact!)
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
//區頭
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return keysArray[section]
}
//索引欄
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return keysArray
}
//允許哪些cell可以編輯
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
//設置編輯樣式
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
//第一個分區插入,其他分區的編輯樣式都是刪除
return indexPath.section == 0 ? .insert : .delete
}
//提交編輯操作
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let key = keysArray[indexPath.section]
var group = contactSource[key]
if editingStyle == .delete {
//刪除一個分區
if group?.count == 1{
//先修改數據源
keysArray.remove(at: indexPath.section)
//根據key值刪除鍵值對
contactSource.removeValue(forKey: key)
//再更新UI
let set = NSIndexSet(index: indexPath.section)
tableView.deleteSections(set as IndexSet, with: .left)
}else{
//逐條刪除cell
//修改數據源
group?.remove(at: indexPath.row)
//對contactSource從新賦值
contactSource[key] = group
//更新UI
tableView.deleteRows(at: [indexPath], with: .right)
}
} else if editingStyle == .insert {
//創建聯系人對象
let aContact = Contact()
aContact.name = "寶寶"
aContact.gender = "女"
aContact.phone = "10086"
group?.append(aContact)
//重新賦值
contactSource[key] = group
//刷新UI
tableView.insertRows(at: [indexPath], with: .left)
//重新加載數據
tableView.reloadData()
}
}
//移動哪些cell
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
//修改數據源
let key = keysArray[fromIndexPath.section]
var group = contactSource[key]
//取出原位置的對象
let aContact = group?[fromIndexPath.row]
//刪除對象
group?.remove(at: fromIndexPath.row)
//插入到移動之后的位置
group?.insert(aContact!, at: to.row)
//重新賦值
contactSource[key] = group
}
//選擇cell時觸發的方法
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailVC = DetailViewController()
let key = keysArray[indexPath.section]
let group = contactSource[key]
let aContact = group?[indexPath.row]
detailVC.aContact = aContact
self.navigationController?.pushViewController(detailVC, animated: true)
}
//移動
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
//限制跨區移動的方法
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if sourceIndexPath.section == proposedDestinationIndexPath.section{
return proposedDestinationIndexPath
}else{
return sourceIndexPath
}
}
DetailViewController
import UIKit
class DetailViewController: UIViewController {
var aContact:Contact!
var photoLabel:UIImageView!
var nameLabel:UILabel!
var phoneLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = #colorLiteral(red: 1, green: 0.8392077942, blue: 0.9732400577, alpha: 1)
self.setupSubviews()
}
func setupSubviews(){
self.setUpData()
if aContact.gender == "男"{
photoLabel.image = #imageLiteral(resourceName: "lr.png")
}
else{
photoLabel.image = #imageLiteral(resourceName: "poto.png")
}
nameLabel.text = aContact.name
nameLabel.text = aContact.phone
}
func setUpData()? {
photoLabel = UIImageView(frame: CGRect(x: 150, y: 100, width: 150, height: 150))
photoLabel.layer.cornerRadius = 75
photoLabel.clipsToBounds = true
self.view.addSubview(photoLabel)
nameLabel = UILabel(frame: CGRect(x: 100, y: 300, width: 250, height: 50))
nameLabel.backgroundColor = UIColor.red
self.view.addSubview(nameLabel)
phoneLabel = UILabel(frame: CGRect(x: 100, y: 380, width: 250, height: 50))
phoneLabel.backgroundColor = UIColor.red
self.view.addSubview(phoneLabel)
}
BoyStudentCell
import UIKit
class BoyStudentCell: UITableViewCell {
var nameLabel:UILabel!
var photoPic:UIImageView!
var saysLabel:UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews(){
//nameLabel
nameLabel = UILabel(frame: CGRect(x: 10, y: 5, width: kScreenWidth - 120, height: 40))
nameLabel.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
self.contentView.addSubview(nameLabel)
//photoPic
photoPic = UIImageView(frame: CGRect(x: kScreenWidth - 110, y: 5, width: 90, height: 90))
// photoPic.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
self.contentView.addSubview(photoPic)
//saysLabel
saysLabel = UILabel(frame: CGRect(x: 10, y: 50, width: kScreenWidth - 120, height: 40))
//saysLabel.backgroundColor = #colorLiteral(red: 0.6136813675, green: 0.6465901778, blue: 1, alpha: 1)
self.contentView.addSubview(saysLabel)
}
func setValueViews(aContact:Contact){
self.photoPic.image = UIImage(named:"lr")
self.nameLabel.text = aContact.name
self.saysLabel.text = aContact.phone
}
override func layoutSubviews()
{
super.layoutSubviews()
self.backgroundColor = UIColor.clear;
for view in self.subviews {
self.backgroundView?.frame = CGRect(x:0, y:0, width:(self.backgroundView?.frame.size.width)!,height: (self.backgroundView?.frame.size.height)!);
if NSStringFromClass(view.classForCoder)? == "UITableViewCellDeleteConfirmationView" { // move delete confirmation view
self.bringSubview(toFront: view)
}
}
}
GirlStudentCell
import UIKit
//獲取屏幕的寬和高
let kScreenWidth = UIScreen.main.bounds.width
let kScreenheight = UIScreen.main.bounds.height
class GirlStudentCell: UITableViewCell {
//屬性定義成私有的
private var photoView:UIImageView!
private var nameLabel:UILabel!
private var saysLabel:UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView(){
photoView = UIImageView(frame: CGRect(x: 10, y: 5, width: 90, height: 90))
photoView.layer.cornerRadius = 45
photoView.clipsToBounds = true
// photoView.backgroundColor = #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)
self.contentView.addSubview(photoView)
nameLabel = UILabel(frame: CGRect(x: 110, y: 5, width: kScreenWidth - 120, height: 40))
nameLabel.backgroundColor = #colorLiteral(red: 1, green: 0.8360928114, blue: 0.8408111242, alpha: 1)
self.contentView.addSubview(nameLabel)
saysLabel = UILabel(frame: CGRect(x: 110, y: 50, width: kScreenWidth - 120, height: 40))
//saysLabel.backgroundColor = #colorLiteral(red: 0.8642925127, green: 0.6110214953, blue: 0.6692668104, alpha: 1)
self.contentView.addSubview(saysLabel)
}
// 封裝一個賦值的方法 ---> 接口
func setValueByContact(contact:Contact){
nameLabel.text = contact.name
photoView.image = UIImage(named:"poto")
saysLabel.text = contact.phone
}
//(此方法可不實現)
override func layoutSubviews()
{
super.layoutSubviews()
self.backgroundColor = UIColor.clear;
for view in self.subviews {
self.backgroundView?.frame = CGRect(x:0, y:0, width:(self.backgroundView?.frame.size.width)!,height: (self.backgroundView?.frame.size.height)!);
if NSStringFromClass(view.classForCoder)? == "UITableViewCellDeleteConfirmationView" { // move delete confirmation view
self.bringSubview(toFront: view)
}
}
}