通讯录(两个界面)

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)

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容