• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift - UITableView

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

创建UITablView

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    
    var Names = ["A","B","C","D","E","F"]
    var tableView:UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建表格图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //将代理,数据来源设为自己
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //创建表头标签
        let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
        headerLabel.text = "Header"
        self.tableView?.tableHeaderView = headerLabel
        
        self.view.addSubview(tableView)
    }
    //设置分区数(不设置默认为1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    //设置单元格数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Names.count
    }
    //设置单元格内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //设置重用单元格名称
        let identifier = "reusedCell"
        //使用重用单元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identify)
        //如果单元格为nil创建重用单元格
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: identify)
        }
        cell?.textLabel?.text = Names[indexPath.row]
        return cell!
    }
    //自定义单元格高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    //点击单元格响应时间
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复
        let cell = tableView.cellForRow(at: indexPath)
        if cell?.accessoryType == UITableViewCell.AccessoryType.none{
            cell?.accessoryType = .checkmark
            print("你选择了:\(String(describing: cell?.textLabel?.text))")
        }else{
            cell?.accessoryType = .none
        }
    }
    
}

使用不同样式单元格

import UIKit

class CustomizeTableViewCell: UITableViewCell {
    var UserImage:UIImageView!
    var UserName:UILabel!
    var Detail:UIButton!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.UserImage = UIImageView(image: UIImage(named: "UserImage"))
        self.UserImage.center = CGPoint(x: 30, y: 22)
        
        self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))
        self.UserName.text = "自定义单元格"
        
        self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))
        self.Detail.setTitle("详情", for: .normal)
        self.Detail.backgroundColor = UIColor.gray
        self.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)
        
        self.addSubview(self.UserName)
        self.addSubview(self.UserImage)
        self.addSubview(self.Detail)
    }
    @objc func showDetail(){
        print("显示详情信息")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

效果图:

自定义UItableViewCell

创建一个Cocoa Touch class文件,设置父类:UITableViewCell,名称为CustomizeTableViewCell

编辑CustomizeTableViewCell:

import UIKit

class CustomizeTableViewCell: UITableViewCell {
    var UserImage:UIImageView!
    var UserName:UILabel!
    var Detail:UIButton!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.UserImage = UIImageView(image: UIImage(named: "UserImage"))
        self.UserImage.center = CGPoint(x: 30, y: 22)
        
        self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))
        self.UserName.text = "自定义单元格"
        
        self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))
        self.Detail.setTitle("详情", for: .normal)
        self.Detail.backgroundColor = UIColor.gray
        self.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)
        
        self.addSubview(self.UserName)
        self.addSubview(self.UserImage)
        self.addSubview(self.Detail)
    }
    @objc func showDetail(){
        print("显示详情信息")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

编辑ViewController:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var user = ["A","B","C"]
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: self.view.frame)
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return user.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell:CustomizeTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? CustomizeTableViewCell
        if cell == nil{
            cell = CustomizeTableViewCell(style: .default, reuseIdentifier: identifier)
        }
        cell?.UserName.text = user[indexPath.row]
        return cell!
    }

}

给文章添加章节和索引

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    
    var Section = ["A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","z"]
    var Content =   [["1","2","3"],["3","4"],["5","6"],["7","8"],["9","10"],["11","12"],["13","14"],["15","16"],["12","21"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"]]
    var tableView:UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建表格图
        self.tableView = UITableView(frame: self.view.frame, style: .grouped)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //创建表头标签
        let headerLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2, y: 0, width: self.view.bounds.width, height: 30))
        headerLabel.text = "添加章节和索引"
        self.tableView?.tableHeaderView = headerLabel
        self.view.addSubview(tableView)
        print(Content.count)
    }
    //设置分区数(不设置默认为1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return Section.count
    }
    //设置单元格数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Content[section].count
    }
    //设置单元格表头
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.Section[section]
    }
    //设置单元格表尾
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        return "有\(self.Content[section].count)个控件"
    }
    //设置索引内容
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.Section
    }
    //设置单元格内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identify)
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: identify)
        }
        let section = indexPath.section
        var data = self.Content[section]
        cell?.textLabel?.text = data[indexPath.row]
        return cell!
    }
    //点击单元格响应时间
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复
        let section = indexPath.section
        var data = self.Content[section]
        let alertController = UIAlertController(title: "提示", message: "你点击了:\(data[indexPath.row])", preferredStyle: .alert)
        let ok = UIAlertAction(title: "确定", style: .default, handler: nil)
        alertController.addAction(ok)
        present(alertController, animated: true, completion: nil)
    }
    
}

单元格的删除,插入,移动

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var SectionNum = ["delete","insert","move"]
    var Content = [["A","B"],["C","D"],["E","F"]]
    var tableView:UITableView!
    override func viewDidLoad() {
     super.viewDidLoad()
        tableView = UITableView(frame: self.view.frame)
        tableView.dataSource = self
        tableView.delegate = self
        //设置是否为编辑模式
        tableView.setEditing(false, animated: true)
        self.view.addSubview(tableView)
        //添加一个手势来开启/关闭编辑模式
        let  
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
iOS 代码混淆(swift版)发布时间:2022-07-13
下一篇:
深入云存储系统Swift存储节点:存储实现分析发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap