UITableView - Swift
在這里就不過多的去介紹object-c中的UITableView與Swift的區別了,直接總結在Swift中的用法,我也是在學習有不足的地方可以共同探討。
Swift中使用TableView和object-c中的流程一樣,同樣需要注冊cell、實現相關的代理方法、cell的重用機制。
import UIKit
let cell_identifier: String = "Cell"
/*
var infoTableView = UITableView()
var itemArr = NSMutableArray()
*/
class SecondViewController: UIViewController,
UITableViewDelegate,
UITableViewDataSource {
var infoTableView:UITableView? = nil //聲明tableView變量
var itemArr:NSMutableArray = [] //聲明可變數組變量
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.white
self.createSubViews()
}
func createSubViews() {
self.itemArr = NSMutableArray.init(array: ["鄭州","開封","洛陽","焦作","新鄉","周口","濟源","漯河","信陽","安陽","許昌"])
//UITableView 初始化
self.infoTableView = UITableView (frame: view.bounds,style: UITableViewStyle.plain)
self.infoTableView?.tableFooterView = UIView()
self.infoTableView?.dataSource = self
self.infoTableView?.delegate = self
self.infoTableView?.setEditing(true, animated: true)
self.view.addSubview(self.infoTableView!)
//注冊 cell
self.infoTableView?.register(UITableViewCell.self, forCellReuseIdentifier: cell_identifier)
//這種注冊cell的方法也可以
//infoTableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cell_identifier)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArr.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cell_identifier, for: indexPath)
cell.textLabel?.text = (itemArr[indexPath.row] as! String)
return cell
}
//分割線從左端頂部顯示(使cell的)分割線與屏幕的左右兩端對齊顯示
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: UITableViewCell.layoutMargins))){
cell.layoutMargins = .zero
}
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
//單獨刪除單元格
if editingStyle == UITableViewCellEditingStyle.delete{
self.itemArr.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with:.top)
print("單獨刪除cell單元格響應!")
let alertCon = UIAlertController.init(title: "提示", message: "您正在進行UItableViewCell的刪除操作,是否刪除?", preferredStyle:UIAlertControllerStyle.actionSheet)
let doneAction = UIAlertAction.init(title: "刪除", style: UIAlertActionStyle.destructive, handler: { (UIAlertAction) -> Void in
print("alertView確定響應!")
})
let cancleAction = UIAlertAction.init(title: "放棄", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in
print("alertView取消響應!")
})
alertCon.addAction(doneAction)
alertCon.addAction(cancleAction)
self.present(alertCon, animated: true, completion: nil)
//插入一個單元格數據
}else if editingStyle == UITableViewCellEditingStyle.insert{
print("insert響應!")
let alertCon = UIAlertController.init(title: "提示", message: "您正在進行UItableViewCell的插入操作?", preferredStyle:UIAlertControllerStyle.alert)
let doneAction = UIAlertAction.init(title: "確定", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in
print("alertView確定響應!")
self.itemArr .insert("鄭州(新增)", at: indexPath.row)
self.infoTableView?.reloadData()
})
let cancleAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in
print("alertView取消響應!")
})
alertCon.addAction(doneAction)
alertCon.addAction(cancleAction)
self.present(alertCon, animated: true, completion: nil)
}
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle{
print("單元格cell刪除設置響應")
//返回的cell的樣式 是帶有選擇按鈕的樣式
//return UITableViewCellEditingStyle(rawValue: UITableViewCellEditingStyle.RawValue(UInt8(UITableViewCellEditingStyle.insert.rawValue)|UInt8(UITableViewCellEditingStyle.delete.rawValue)))!
return UITableViewCellEditingStyle.delete
}
//自定義左滑顯示項目 (實現此代理方法時需要設置TableView的setEditing為NO 否則沒有實際的效果, 也可以設置代理editingStyleForRowAt返回UITableViewCellEditingStyle.delete 此時點擊cell左側的按鈕cell會自動向左側滑呼出自定義的操作按鈕)
/*func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//刪除操作
let deleteAction = UITableViewRowAction.init(style: .default, title: "刪除", handler: {_,_ in
})
deleteAction.backgroundColor = UIColor.red
let editAction = UITableViewRowAction.init(style: UITableViewRowActionStyle.normal, title: "編輯", handler: {_,_ in
})
let insertAction = UITableViewRowAction.init(style: UITableViewRowActionStyle.normal, title: "插入", handler: {_,_ in
})
insertAction.backgroundColor = UIColor.blue
let topAction = UITableViewRowAction.init(style: UITableViewRowActionStyle.normal, title: "置頂", handler: {_,_ in
})
editAction.backgroundColor = UIColor.green
return [deleteAction,editAction,insertAction,topAction]
}*/
//是否允許cell進行編輯 默認允許
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
//是否允許cell排序
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
print("是否允許cell排序的響應!")
return true
}
//cell排序操作
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
self.infoTableView?.moveRow(at: sourceIndexPath, to: destinationIndexPath)
self.itemArr.exchangeObject(at: sourceIndexPath.row, withObjectAt: destinationIndexPath.row)
print("cell排序響應!")
}
//選中某個 cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("cell點擊響應")
}
//如果需要實現cell按下高亮,手放開恢復原狀態,則實現如下方法即可:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
效果如下圖所示:

自定義cell側滑操作按鈕效果:

public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle{
//返回的cell的樣式 是帶有選擇按鈕的樣式
return UITableViewCellEditingStyle(rawValue: UITableViewCellEditingStyle.RawValue(UInt8(UITableViewCellEditingStyle.insert.rawValue)|UInt8(UITableViewCellEditingStyle.delete.rawValue)))!
}
效果如下:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
//此代理方法 返回UITableViewCellEditingStyle.delete cell是刪除的效果如下圖1
//返回UITableViewCellEditingStyle.insert 是插入添加的效果 如下圖2
圖一:

圖二:
歡迎大家的騷擾
