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

}


請大家參考學習,希望能對初學的小白有幫助。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章