通讯录(按照两种不同的cell,按性别区分)
在ViewController.swift中键入:
在Main.storyboard中Editor->Embed in->Navigation Controller添加导航栏
import UIKit
enum Gender {
case Boy
case Girl
}
class Person {
var gender:Gender! = nil
var group:Character! = nil
var name:String! = nil
var phoneNumber:String! = nil
var img:String! = nil
}
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//全部的联系人
var dic:[Character :[Person]] = [Character:[Person]]()
//联系人的分组
var sortArr:[Character] = [Character]()
var tableView:UITableView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.title = "通讯录"
self.tableView = UITableView(frame: self.view.bounds, style: .plain)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.view.addSubview(self.tableView!)
//注册两个cell(男和女)
self.tableView?.register(ManTableViewCell.self, forCellReuseIdentifier: "Boy")
self.tableView?.register(WomanTableViewCell.self, forCellReuseIdentifier: "Girl")
//添加右上角的那个(“+”)
let item = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(rightItem))
self.navigationItem.rightBarButtonItem = item
self.load()
}
//“+”的方法
func rightItem() {
let sec = SecondViewController()
sec.operate = .Add
weak var weakSelf = self
sec.AddPersonBlock = {
weakSelf?.insertPerson(p: $0)
weakSelf?.tableView?.reloadData()
}
self.navigationController?.pushViewController(sec, animated: true)
}
//制造假数据(开始运行的时候不为空)
func load(){
let p = Person()
p.name = "Liliy"
p.phoneNumber = "456765"
p.gender = .Girl
p.group = "L"
p.img = "person"
insertPerson(p: p)
let p1 = Person()
p1.name = "Helen"
p1.phoneNumber = "43565-4665"
p1.gender = .Boy
p1.group = "H"
p1.img = "person"
insertPerson(p: p1)
}
// 插入联系人
func insertPerson(p: Person) {
// 根据联系人的分组情况看大字典有没有这个人的分组
let groupArr = dic[p.group]
if groupArr == nil { // 没有这个分组
// 创建一个分组
var arr = [Person]()
arr.append(p)
// 把分组放在字典中
dic[p.group] = arr
} else { // 直接联系人插入
dic[p.group]?.append(p)
}
// 因为字典是无序的, 不能按照 a-z展示分组,所以要排序
sortArr.removeAll()
for item in dic.keys {
sortArr.append(item)
}
// 排序
sortArr.sort {
return $0 < $1
}
}
//返回多少行
func numberOfSections(in tableView: UITableView) -> Int {
return dic.keys.count
}
//返回多少组
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 当前分组对应的key
let group = sortArr[section]
// 取出分组中的元素
let arr = dic[group]
// 返回元素的个数
return (arr?.count)!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 取出person对象, 根据person对象确定使用哪种cell
// 取出分组中的元素
let group = sortArr[indexPath.section]
let arr = dic[group]
let p = arr?[indexPath.row]
// 根据人判断使用哪种cell
if p?.gender == .Girl { // 女
let cell = tableView.dequeueReusableCell(withIdentifier: "Girl",for:indexPath) as! WomanTableViewCell
cell.image2?.image = UIImage(named: (p?.img)!)
cell.name?.text = p?.name
cell.number?.text = p?.phoneNumber
cell.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
cell.accessoryType = .detailButton
return cell
} else { // 男
let cell = tableView.dequeueReusableCell(withIdentifier: "Boy",for:indexPath) as! ManTableViewCell
cell.image1?.image = UIImage(named: (p?.img)!)
cell.name?.text = p?.name
cell.number?.text = p?.phoneNumber
cell.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
cell.accessoryType = .detailButton
return cell
}
}
//分组标题
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let group = sortArr[section]
return "\(group)"
}
//点击单元格
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//先取出单元格对应的模型
let group = sortArr[indexPath.section]
let arr = dic[group]
let p = arr?[indexPath.row]
//传递到下一个界面
let sec = SecondViewController()
sec.operate = .Update
sec.person = p
sec.indexP = indexPath
weak var weakSelf = self
sec.UpdateBlock = {
weakSelf?.dic[(weakSelf?.sortArr[$1.section])!]?[$1.row] = $0
weakSelf?.tableView?.reloadData()
}
//推出下一个控制器
self.navigationController?.pushViewController(sec, animated: true)
}
}
command+n 创建一个Cocoa Touch Class 名为WomanTableViewCell.swift
import UIKit
class WomanTableViewCell: UITableViewCell {
var name:UILabel! = nil
var image2:UIImageView! = nil
var number:UILabel! = nil
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.name = UILabel(frame:CGRect(x: 90, y: 10, width: 100, height: 30))
self.addSubview(self.name!)
self.number = UILabel(frame: CGRect(x: 90, y: 30, width: 200, height: 40))
self.addSubview(self.number!)
self.image2 = UIImageView(frame: CGRect(x: 10, y: 20, width: 50, height: 40))
self.addSubview(self.image2!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
command+n 创建一个Cocoa Touch Class 名为ManTableViewCell.swift
import UIKit
class ManTableViewCell: UITableViewCell {
var name:UILabel! = nil
var image1:UIImageView! = nil
var number:UILabel! = nil
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.name = UILabel(frame:CGRect(x: 100, y: 10, width: 200, height: 40))
self.addSubview(self.name!)
self.number = UILabel(frame: CGRect(x: 240, y: 10, width: 200, height: 40))
self.addSubview(self.number!)
self.image1 = UIImageView(frame: CGRect(x: 10, y: 20, width: 50, height: 40))
self.addSubview(self.image1!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
创建第二个ViewController名为SecondViewController
import UIKit
enum Do {
case Add
case Update
}
class SecondViewController: UIViewController {
var nameTextField:UITextField! = nil
var phoneTextField:UITextField! = nil
var btn:UIButton! = nil
var img:UITextField! = nil
var genderTextField:UITextField! = nil
var groupTextField:UITextField! = nil
//记录当前是更新还是添加
var operate : Do! = nil
//如果是更新传递过来一个对象
var person:Person!=nil
// 更新的闭包 1. p 2. 多少组,多少行
var UpdateBlock: ((Person,IndexPath)->Void)? = nil
// 添加的闭包 1. p
var AddPersonBlock:((Person)->Void)? = nil
// 更新时候P的下标
var indexP: IndexPath? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField = UITextField(frame: CGRect(x: 40, y: 100, width: 100, height: 40))
self.nameTextField?.placeholder = "姓名"
self.nameTextField?.borderStyle = .bezel
self.view.addSubview(self.nameTextField!)
self.phoneTextField = UITextField(frame: CGRect(x: 40, y: 200, width: 100, height: 40))
self.phoneTextField?.placeholder = "电话"
self.phoneTextField?.borderStyle = .bezel
self.view.addSubview(self.phoneTextField!)
self.img = UITextField(frame: CGRect(x: 40, y: 450, width: 100, height: 40))
self.img?.placeholder = "显示头像"
self.img?.borderStyle = .bezel
self.view.addSubview(self.img!)
self.genderTextField = UITextField(frame: CGRect(x: 40, y: 300, width: 100, height: 40))
self.genderTextField?.placeholder = "性别"
self.genderTextField?.borderStyle = .bezel
self.view.addSubview(self.genderTextField!)
self.view.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
self.btn = UIButton(type: .system)
self.btn?.frame = CGRect(x: 100, y: 500, width: 40, height: 30)
self.btn?.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
self.btn?.setTitle("保存", for: .normal)
self.view.addSubview(self.btn!)
self.groupTextField = UITextField(frame: CGRect(x: 40, y: 380, width: 100, height: 40))
self.groupTextField?.placeholder = "分组"
self.groupTextField?.borderStyle = .bezel
self.view.addSubview(self.groupTextField!)
//判断更新还是添加
if self.operate == .Add { // 添加操作
self.btn.setTitle("添加", for:.normal)
} else { // 更新操作, 需要给textfield赋值
self.btn.setTitle("更新", for: .normal)
self.nameTextField.text = person.name
self.phoneTextField.text = person.phoneNumber
var str = ""
str.append(person.group)
self.groupTextField.text = str
self.img.text = person.img
// 性别
if person.gender == .Girl {
self.genderTextField.text = "女"
} else {
self.genderTextField.text = "男"
}
}
}
func btnAction(){
// 不管添加还是更新, 都需要根据textfield创建一个对象传递到第一个界面
let p = Person()
p.name = self.nameTextField.text
if self.genderTextField.text == "男" {
p.gender = .Boy
} else {
p.gender = .Girl
}
p.phoneNumber = self.phoneTextField.text
p.group = self.groupTextField.text?.characters[(self.groupTextField.text?.startIndex)!]
p.img = "person"
if self.operate == .Add { // 添加
self.AddPersonBlock!(p)
} else { //更新
self.UpdateBlock!(p,indexP!)
}
}
}
***运行结果如下图