Swift-根据数据源展示数据

文件图例.png

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        self.window = UIWindow(frame: UIScreen.main.bounds)

        self.window?.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)

        self.window?.makeKeyAndVisible()//设置主屏幕并可见

        //创建导航视图控制器的根视图
        let rootVC = ContactsTableViewController()

        //创建导航视图控制器,并为他指定根视图控制器
        let navigation = UINavigationController(rootViewController: rootVC)

        //将导航视图控制器设置器设置为window的根视图控制器
        self.window?.rootViewController = navigation
        return true
    }

ContactsTableViewController.swift

import UIKit

class ContactsTableViewController: UITableViewController {

    var contactsource:[String:[Contacts]] = Dictionary()

    let girlcellReuseiden = "girl"

    let boycellReuseiden = "boy"

    var keysArray:[String] = Array()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "通讯录"

        self.creatdata()

        self.tableView.register(GirlTableViewCell.self, forCellReuseIdentifier: girlcellReuseiden)

        self.tableView.register(BoyTableViewCell.self, forCellReuseIdentifier: boycellReuseiden)

        //var keys = self.dic.keys

        //keysArray = keys.sorted()

        self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    func creatdata() {
        var 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"]
            ]
        ]

        for key in dic.keys {

            let array = dic[key]

            var group:[Contacts] = Array()

            for dictionary in array! {

                let contact = Contacts(dict: dictionary)
                group.append(contact)
            }
            contactsource[key] = group
        }
        let keys = contactsource.keys
        keysArray = keys.sorted()

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return contactsource.count /*keysArray.count*/
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let key = keysArray[section]

        let group = contactsource[key]/*dic[key]*/

        return group!.count
    }

    /**/
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let key = keysArray[indexPath.section]

        let group = contactsource[key]/*dic[key!]*/

        let con = group?[indexPath.row]

        if con?.gender == "男" {

            let cell = tableView.dequeueReusableCell(withIdentifier: boycellReuseiden) as! BoyTableViewCell

            cell.setvalueviews(con: con!)

            return cell

        }else{

            let cell = tableView.dequeueReusableCell(withIdentifier: girlcellReuseiden) as! GirlTableViewCell

            //调用接口为cell赋值
            cell.setValueByContacts(con: con!)

            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
    }

    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 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        //先取出选中cell所在的分区对应的key值
        let key = keysArray[indexPath.section]

        //根据key值取出对应的value值数组
        var group = contactsource[key]


        if editingStyle == .delete {

            if group?.count == 1 {

                //删除整个分区
                //1.删除字典中的键值对
                //dic.removeValue(forKey: key!)

                //2.删除排好序的keysArray数组中元素
                keysArray.remove(at: indexPath.section)

                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)

                //删除之后重新为字典中的key对应的value赋值
                contactsource[key] = group

                //更新UI
                tableView.deleteRows(at: [indexPath], with: .fade)

            }

        } else if editingStyle == .insert {

            //准备要插入的数据
            let name = Contacts()

            name.name = "范宇亮"
            name.gender = "男"
            name.phone = "13529704561"

            //先修改数据源
            group?.append(name)

            //重新为字典contactsource的键值对赋值
            contactsource[key] = group

            //更新UI
            tableView.insertRows(at: [indexPath], with: .right)

            //让tableview重新加载数据
            self.tableView.reloadData()

        }


    }

    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {

        return true
    }

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

        //修改数据源
        let key = keysArray[fromIndexPath.section]

        var group = contactsource[key]

        //先取出数组中原位置的元素
        let name = group?[fromIndexPath.row]

        //删除数组中原来位置的元素
        group?.remove(at: fromIndexPath.row)

        //插入数组中新的位置
        group?.insert(name!, at: to.row)

        //重新对字典中key值对应的value值赋值
        contactsource[key] = group

    }

    override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {

        if sourceIndexPath.section == proposedDestinationIndexPath.section{
            return proposedDestinationIndexPath
        }else{
            return sourceIndexPath
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let ContactsVC = ContactsViewController()

        let key = keysArray[indexPath.section]

        let group = contactsource[key]

        let c = group?[indexPath.row]

        ContactsVC.contacts = c

        self.navigationController?.pushViewController(ContactsVC, animated: true)

    }

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

ContactsViewController.swift

import UIKit

class ContactsViewController: UIViewController {

    var contacts:Contacts!


    var photoimage:UIImageView!
    var namelabel:UILabel!
    var phonelabel:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white

        self.setupView()

        namelabel.text = contacts.name
        phonelabel.text = contacts.phone



    }

    func setupView() {

        photoimage = UIImageView(frame: CGRect(x: kscrollWidth*0.5 - 100, y: 100, width: 200, height: 200))

        photoimage.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)

        photoimage.layer.cornerRadius = 100

        photoimage.clipsToBounds = true

        if contacts.gender == "男" {
            photoimage.image = UIImage(named: "liuxuyao")
        }else{
            photoimage.image = UIImage(named: "fanbingbing")
        }

        self.view.addSubview(photoimage)

        namelabel = UILabel(frame: CGRect(x: kscrollWidth*0.5-150, y: 350, width: 300, height: 50))

        namelabel.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)

        namelabel.textAlignment = .center

        namelabel.font = UIFont.systemFont(ofSize: 24.0, weight: 0.3)

        self.view.addSubview(namelabel)

        phonelabel = UILabel(frame: CGRect(x: kscrollWidth*0.5-150, y: 450, width: 300, height: 50))

        phonelabel.backgroundColor = #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)

        phonelabel.textAlignment = .center

        phonelabel.font = UIFont.systemFont(ofSize: 20.0, weight: 0.2)

        self.view.addSubview(phonelabel)
    }
}

Contacts.swift

import UIKit

class Contacts: NSObject {

    var name:String!
    var gender:String!
    var phone:String!

    override init() {
        super.init()
    }

    init(name:String,gender:String,phone:String) {

        self.name = name
        self.gender = gender
        self.phone = phone

    }

    init(dict:Dictionary<String,String>) {
        self.name = dict["name"]
        self.gender = dict["gender"]
        self.phone = dict["phone"]
    }

}

GirlTableViewCell.swift

import UIKit

let kscrollWidth = UIScreen.main.bounds.width
let kscrollHight = UIScreen.main.bounds.height

class GirlTableViewCell: UITableViewCell {

   private var labelname:UILabel!
   private var labelphone:UILabel!
   private var photo:UIImageView!

   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
       super.init(style: style, reuseIdentifier: reuseIdentifier)

       self.setupView()
   }

   func setupView() {
       photo = UIImageView(frame: CGRect(x: 10, y: 5, width: 90, height: 90))

       photo.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)

       photo.layer.cornerRadius = 45

       photo.clipsToBounds = true

       //        photo.image = UIImage(named: "fanbingbing")

       self.contentView.addSubview(photo)

       labelname = UILabel(frame: CGRect(x: 110, y: 5, width: 294, height: 40))

       labelname.backgroundColor = #colorLiteral(red: 1, green: 0.5409764051, blue: 0.8473142982, alpha: 1)

       labelname.textAlignment = .center

       self.contentView.addSubview(labelname)

       labelphone = UILabel(frame: CGRect(x: 110, y: 50, width: 294, height: 40))

       labelphone.backgroundColor = #colorLiteral(red: 0.8446564078, green: 0.5145705342, blue: 1, alpha: 1)

       labelphone.font = UIFont.systemFont(ofSize: 14.0)

       labelphone.textAlignment = .center

       labelphone.numberOfLines = 2

       self.contentView.addSubview(labelphone)

   }
   func setValueByContacts(con:Contacts) {

       labelname.text = con.name
       labelphone.text = con.phone
       photo.image = UIImage(named: "fanbingbing")

   }
   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)

           }
       }
   }
   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
   
}

BoyTableViewCell.swift

import UIKit

class BoyTableViewCell: UITableViewCell {

    var labelname:UILabel!
    var labelphone:UILabel!
    var photo:UIImageView!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.setupView()
    }

    func setupView() {

        labelname = UILabel(frame: CGRect(x: 10, y: 5, width: 294, height: 40))

        labelname.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)

        labelname.textAlignment = .center

        self.contentView.addSubview(labelname)

        labelphone = UILabel(frame: CGRect(x: 10, y: 50, width: 294, height: 40))

        labelphone.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)

        labelphone.textAlignment = .center

        labelphone.font = UIFont.systemFont(ofSize: 14.0)

        labelphone.numberOfLines = 2

        self.contentView.addSubview(labelphone)

        photo = UIImageView(frame: CGRect(x: 314, y: 5, width: 90, height: 90))

        photo.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)

        //        photo.image = UIImage(named: "liuxuyao")

        self.contentView.addSubview(photo)

    }

    func setvalueviews(con:Contacts) {
        self.photo.image = UIImage(named: "liuxuyao")

        self.labelname.text = con.name
        self.labelphone.text = con.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)

            }
        }
    }

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

推荐阅读更多精彩内容

  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子阅读 8,497评论 0 35
  • 目录Swift学习资料@完整App@App框架@ 响应式框架@ UI@ 日历三方库@下拉刷新@模糊效果@富文本@图...
    IOS开发攻城狮_Fyc阅读 6,282评论 1 90
  • Ylan111阅读 170评论 0 0
  • 10月15号 星期日 晴 今天周日,女儿作业做完了,看我有空闲时间,央求我和她一起玩。我寻思玩什么呢?做题?...
    刘婧爸爸阅读 118评论 0 0
  • 转眼间10月份已经过去一半了,第一周的时间是在假期里度过,第二周进行了新的工作和生活。 1.工作方面 假期过后的第...
    玲玲同学阅读 291评论 4 4