众所周知,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
}
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]
}
}