swift3.0 UITableView实例

众所周知,swift语言凭借其简单的语法以及便捷的使用获得很多开发者的好评,同时也面临着更新换代较快的困扰,今天我将自己练习写的UITableView的基本使用方法贴在下边,供大家借鉴。该工程实现了列表的删除,添加,排序以及置顶,具体功能代码可根据注释进行查询。该工程为纯代码手写,单纯为了初学者好掌握,当然我自己也是这两天才开始自学的,有不足之处还请大家批评指正。

AppDelegate.swift只是粘贴了常用的一个方法的代码

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow(frame:UIScreen.main.bounds)
        let rootVC = ViewController()
        let nav = UINavigationController(rootViewController:rootVC)
        self.window?.rootViewController = nav
        return true
    }

ViewController.swift

import UIKit

let cellIdentifier = "cellIdentifier"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
    var mytableView:UITableView? = nil
    var itemArray:NSMutableArray = []
    var oldIndexPath:IndexPath? = nil
    var isSelected:Bool = false
    var editButton:UIButton? = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.backgroundColor = UIColor.white
        self.itemArray = NSMutableArray.init(array: ["北京", "上海", "天津", "海南", "南京", "三亚", "青岛", "济南", "香港", "澳门", "安徽"])
        initView()
        setUpEditButton()
        setUpAddButton()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
    }
    
    // MARK: - 创建界面
    //初始化tableview
    func initView() {
        self.mytableView = UITableView(frame:CGRect(x:0, y:0, width:self.view.frame.size.width, height:self.view.frame.size.height - 10), style:UITableViewStyle.plain)
        self.mytableView!.delegate = self
        self.mytableView!.dataSource = self
        self.mytableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        self.view.addSubview(self.mytableView!)
        
        let footerView = UIView.init(frame: CGRect(x:0, y:0, width:self.view.frame.size.width, height:0.5))
        footerView.backgroundColor = UIColor.init(colorLiteralRed: 217/255.0, green: 217/255.0, blue: 217/255.0, alpha: 1)
        self.mytableView?.tableFooterView = footerView
    
        /*分割线左侧顶部显示,与代理方法有同样效果
        if(mytableView?.responds(to: #selector(setter: UITableViewCell.separatorInset)))!{
            mytableView?.separatorInset = .zero
        }
        
        if(mytableView?.responds(to: #selector(setter: UIView.layoutMargins)))!{
            mytableView?.layoutMargins = .zero
        }
        */
    }
    
    //添加左侧编辑按钮
    func setUpEditButton() {
        self.editButton = UIButton.init(type: .custom)
        self.editButton?.frame = CGRect(x:0, y:0, width:40, height:20)
        self.editButton?.addTarget(self, action: #selector(editButtonTapped), for: .touchUpInside)
        self.editButton?.setTitle("编辑", for: .normal)
        self.editButton?.backgroundColor = UIColor.red
        self.editButton?.tag = 100
        let leftBarButtonItem = UIBarButtonItem.init(customView: self.editButton!)
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
    }
    
    //添加右侧添加按钮
    func setUpAddButton() {
        let addButton = UIButton.init(type: .custom)
        addButton.frame = CGRect(x:0, y:0, width:40, height:20)
        addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
        addButton.setTitle("添加", for: .normal)
        addButton.backgroundColor = UIColor.red
        let rightBarButtonItem = UIBarButtonItem.init(customView: addButton)
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    
    // MARK: - 按钮点击事件
    //编辑事件
    func editButtonTapped() {
        if editButton?.tag == 100 {
            self.editButton?.setTitle("完成", for: .normal)
            self.mytableView?.setEditing(true, animated: true)
            self.editButton?.tag = 200
        } else {
            self.editButton?.setTitle("编辑", for: .normal)
            self.mytableView?.setEditing(false, animated: true)
            self.editButton?.tag = 100
        }
    }
    
    //添加事件
    func addButtonTapped() {
        self.editButton?.setTitle("编辑", for: .normal)
        self.mytableView?.setEditing(false, animated: true)
        self.editButton?.tag = 100
        self.itemArray.insert("新疆", at: 0)
        self.mytableView?.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .top)
    }

    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.itemArray.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = String(describing: self.itemArray[indexPath.row])
        cell.selectionStyle = .none
        return cell
    }
    
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 80
    }
    
    //是否允许排序
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //排序操作
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        self.mytableView?.moveRow(at: sourceIndexPath, to: destinationIndexPath)
        self.itemArray.exchangeObject(at: sourceIndexPath.row, withObjectAt: destinationIndexPath.row)
    }
    
    //只选中一个单元格
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let newCell = tableView.cellForRow(at: indexPath)
        if oldIndexPath == nil {
            newCell?.accessoryType = .checkmark
            isSelected = true
        } else if oldIndexPath != indexPath {
            let oldCell = tableView.cellForRow(at: self.oldIndexPath!)
            oldCell?.accessoryType = .none
            newCell?.accessoryType = .checkmark
            isSelected = true
        } else if oldIndexPath == indexPath {
            if isSelected {
                newCell?.accessoryType = .none
                isSelected = false
            }else {
                newCell?.accessoryType = .checkmark
                isSelected = true
            }
        }
        
        oldIndexPath = indexPath
    }
    
    //分割线从左端顶部显示
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        if(cell.responds(to: #selector(setter: UITableViewCell.separatorInset))){
            cell.separatorInset = .zero
        }
        
        if(cell.responds(to: #selector(setter: UIView.layoutMargins))){
            cell.layoutMargins = .zero
        }
    }
    
    /*单独删除单元格
    public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
        self.itemArray.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with:.top)
    }
    
    public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle{
        return .delete
    }*/

    //自定义左滑显示项目
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        //删除操作
        let deleteAction = UITableViewRowAction.init(style: .default, title: "删除", handler: {_,_ in
            self.itemArray.removeObject(at: indexPath.row)
            self.mytableView!.deleteRows(at: [indexPath], with:UITableViewRowAnimation.left)
            self.editButton?.setTitle("编辑", for: .normal)
            self.mytableView?.reloadData()
            self.mytableView?.setEditing(false, animated: true)
            self.editButton?.tag = 100
        })
        
        
        //置顶操作
        let firstAction = UITableViewRowAction.init(style: .normal, title: "置顶", handler: {_,_ in
            self.mytableView!.moveRow(at: indexPath, to: IndexPath.init(row: 0, section: 0))
            let string = self.itemArray[indexPath.row]
            self.itemArray.removeObject(at: indexPath.row)
            self.itemArray.insert(string, at: 0)
            self.editButton?.setTitle("编辑", for: .normal)
            self.mytableView?.setEditing(false, animated: true)
            self.editButton?.tag = 100
        })
        firstAction.backgroundColor = UIColor.blue
        
        return [deleteAction, firstAction]
    }

}


请大家参考学习,希望能对初学的小白有帮助。



  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好,关于 Swift 封装 UITableView 和 UICollectionView 的问题,我可以给你一些基本的介绍。 首先,UITableView 和 UICollectionView 都是 iOS 平台中常用的视图控件,用于展示列表和网格等数据。在 Swift 中,我们可以通过继承 UITableView 和 UICollectionView 类来自定义我们自己的表格和网格视图。 下面是一个简单的示例代码,展示如何封装 UITableView: ```swift import UIKit class MyTableView: UITableView, UITableViewDataSource, UITableViewDelegate { var data: [String] = [] override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.dataSource = self self.delegate = self // 注册单元格 self.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // UITableViewDataSource 协议方法 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = self.data[indexPath.row] return cell } // UITableViewDelegate 协议方法 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("选中了第 \(indexPath.row) 行") } } ``` 在这个示例代码中,我们自定义了一个名为 `MyTableView` 的类,继承自 `UITableView`。我们在 `init` 方法中设置了数据源和代理,并注册了一个单元格类型。在 `UITableViewDataSource` 和 `UITableViewDelegate` 协议方法中,我们实现了表格的行数、单元格内容和选中事件的处理。 类似地,我们也可以使用类似的方式封装 UICollectionView。需要注意的是,UICollectionViewDelegate 和 UICollectionViewDataSource 两个协议方法和 UITableView 中的函数名和实现方式略有不同,需要根据实际情况来进行调整。 希望这个简单的示例代码可以对你有所帮助。如果你有其他关于 Swift 的问题,欢迎随时提出!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值