UITableView --Swift

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19678579/article/details/77479624

一. 在 ViewController 中添加 UITableView

1. 创建一个 UIViewcontroller 文件

//
//  RefreshVC.swift
//  网络请求Demo
//
//  Created by ZE KANG on 2017/8/21.
//  Copyright © 2017年 LRY. All rights reserved.
//

import UIKit

import Alamofire

var kSize=UIScreen.main.bounds;

var dataTable:UITableView!
var itemStringArr=["企划部","软件部","咨询部","人事部","后勤部","产品部"]


class RefreshVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var titleArr = Array<String>();
    var picArr = [String]();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        initUI();
        methodForSwift();

    }

    func initUI() -> Void {
        self.title = "刷新"
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1);


    }

    //MARK:- Networking
    /// Swift 的 Alamofire
    func methodForSwift() -> Void {
        //        let urlStr = "\(SERVICE_URL)type=\(TOP)&key=\(APPKEY)"

        let parameters = [
            "pag": "2",
            "id": "144f248abf9789911c8ab1e903ec0f10"
        ]
        Alamofire.request(kUrl, method: .post, parameters: parameters).responseJSON { (returnResult) in
            print("secondMethod --> 参数 --> returnResult = \(returnResult.value as Any)")


            //字典接收 JSon 数据
           let dataDict = returnResult.value as! [String : Any] ;
            //从字典中根据 key 提取 value 为数组的数据
            let dataArr = dataDict["data"] as! [Any];
            for dic in dataArr{
                print("title 数值: ",dic);
                //从数组中提取字典
                let anDict = dic as! [String : Any];
                //从字典中提值
                let userFaceStr = anDict["userFace"] as! String ;
                print("提取单个图片=地址: ",userFaceStr);
                let picStr = anDict["userFace"] as! String ;
                let titleStr = anDict["title"] as! String ;

                self.titleArr.append(titleStr);
                self.picArr.append(picStr);
            }
//             print("title 数租: ",self.titleArr);
            //主线程刷新 UI
            DispatchQueue.main.async {
                 self.makeTable();
                 self.forInArrayHandel();
            }
        }
    }

   //MARK:- forIn 数组
    func forInArrayHandel() -> Void {
        for title in self.titleArr{
             print("title 数值: ",title);
        }
    }

    // MARK:- 创建table
    func makeTable (){

        dataTable=UITableView.init(frame: CGRect(x: 0.0, y: 64, width: kSize.width, height: kSize.height-64), style:.plain)
        dataTable.backgroundColor = UIColor.groupTableViewBackground;
        dataTable.delegate=self;//实现代理
        dataTable.dataSource=self;//实现数据源
        dataTable.showsVerticalScrollIndicator = false
        dataTable.showsHorizontalScrollIndicator = false
        self.view.addSubview(dataTable)


        //tableFooter
        dataTable.tableFooterView = UIView.init()

        //MARK:注册 xib Cell(没有 xib)
//        dataTable .register(RefreshCell.classForCoder(), forCellReuseIdentifier: "identti")

        //MARK:注册 xib Cell(使用 xib)
        let cellNib = UINib(nibName: "RefreshCell", bundle: nil)
        dataTable.register(cellNib, forCellReuseIdentifier: "identti")
    }

    // MARK: -table代理

    //段数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }

    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return itemStringArr.count
        return self.titleArr.count;
    }

    //行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 80
    }

    /*
     //头部高度
     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     return 0.01
     }

     //底部高度
     func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
     return 0.01
     }
     */

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

        /*
         let indentifier = "CellA"
         var cell:TableViewCellA! = tableView.dequeueReusableCell(withIdentifier: indentifier) as? TableViewCellA
         if cell == nil {
         cell=TableViewCellA(style: .default, reuseIdentifier: indentifier)
         }


         return cell!
         */

        //MARK: 没有创建 TabelViewCell 文件,直接在本 VC 中复用
        /*
        let identifier="identtifier";
        var cell=tableView.dequeueReusableCell(withIdentifier: identifier)
        if(cell == nil){
            cell=UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: identifier);
        }


          cell?.textLabel?.text = self.titleArr[indexPath.row];
        cell?.detailTextLabel?.text = "待添加内容";
        cell?.detailTextLabel?.font = UIFont .systemFont(ofSize: CGFloat(13))
        cell?.accessoryType=UITableViewCellAccessoryType.disclosureIndicator   //右边小箭头

        return cell!
         */

        //MARK:另外创建了 TabelViewCell 文件
        let cell:RefreshCell = tableView.dequeueReusableCell(withIdentifier: "identti", for: indexPath) as! RefreshCell
         cell.titleLabel?.text = self.titleArr[indexPath.row];
        //定义URL对象
        let url = URL(string:  self.picArr[indexPath.row])
        //从网络获取数据流
        let data = try! Data(contentsOf: url!)
        //通过数据流初始化图片
        let newImage = UIImage(data: data)
        cell.picImg.image = newImage;
        print("图片: ",self.picArr[indexPath.row])

        return cell;
    }

    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        print("indexPath.row = SelectRow第\(indexPath.row)行")
    }

    //取消选中cell时,触发这个代理
    public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath){
        print("indexPath.row = DeselectRow第\(indexPath.row)行")
    }

    //允许编辑cell
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //右滑触发删除按钮
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.init(rawValue: 1)!
    }

    //点击删除cell时触发
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        print("indexPath.row = editingStyle第\(indexPath.row)行")

    }


}

2. 创建 UITableViewCell 文件

//
//  RefreshCell.swift
//  网络请求Demo
//
//  Created by ZE KANG on 2017/8/21.
//  Copyright © 2017年 LRY. All rights reserved.
//

import UIKit



class RefreshCell: UITableViewCell {








    @IBOutlet weak var titleLabel: UILabel!

    @IBOutlet weak var picImg: UIImageView!

    //MARK:- 没有创建xib 文件初始化方法
    /*
    override init(style: UITableViewCellStyle, reuseIdentifier: String?){

        super . init(style: style, reuseIdentifier: reuseIdentifier)

//        self.contentView .addSubview(self.titleLable)
    }

    //懒加载label
    lazy var  titleLable:UILabel = {
        let  titleLable =  UILabel(frame:CGRect.init(x: 100, y: 0, width: 100, height: 30))
        print("----------888")
        titleLable.backgroundColor = .green
        titleLable.textAlignment = NSTextAlignment.center
        return titleLable

    }( )

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

     */
    // MARK:- 创建了 xib 的所使用的方法
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        //此处写 xib 的初始化代码

    }


    //懒加载label


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        self.picImg.backgroundColor = UIColor.yellow;
    }

}

3. 要点:

P1. 在 VC 中

  • 直接复用

  • 有创建 xib 的 cell

   

  • 没有 xib 的 cell
       

P2: 在 TabelViewCell 中

  • xib拖控件

  • 没xib拖控件



效果图:

猜你喜欢

转载自blog.csdn.net/qq_19678579/article/details/77479624