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") } }
建立一個Cocoa Touch class文件,設置父類:UITableViewCell,名稱爲CustomizeTableViewCellswift
編輯CustomizeTableViewCell:ide
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:ui
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 Tap = UITapGestureRecognizer(target: self, action: #selector(OpenEdit)) Tap.numberOfTapsRequired = 2 Tap.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(Tap) } @objc func OpenEdit(){ if self.tableView.isEditing{ tableView.setEditing(false, animated: true) }else{ tableView.setEditing(true, animated: true) } } //設置區域數 func numberOfSections(in tableView: UITableView) -> Int { return SectionNum.count } //設置行數 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let data = Content[section] return data.count } //設置內容 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "reusedCell" var cell = tableView.dequeueReusableCell(withIdentifier: identifier) if cell == nil{ cell = UITableViewCell(style: .default, reuseIdentifier: identifier) } let data = Content[indexPath.section] cell?.textLabel?.text = data[indexPath.row] return cell! } //設置章節名稱 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return SectionNum[section] } //設置編輯狀態下顯示的圖標(none,insert,delete三種圖案) func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if indexPath.section == 0{ return UITableViewCell.EditingStyle.delete }else if indexPath.section == 1{ return UITableViewCell.EditingStyle.insert } return UITableViewCell.EditingStyle.none } //使用刪除,插入執行此方法 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ self.Content[indexPath.section].remove(at: indexPath.row) //刪除選項,並設置刪除的效果 //更新表格數據 self.tableView.reloadData() }else { self.Content[indexPath.section].insert("F", at: indexPath.row) self.tableView.reloadData() } } //修改刪除提示的問題 func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "X" } //設置單元格的位置能夠拖動 func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { if indexPath.section == 2{ return true } return false } //移動完單元格調用此方法 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { print("你使用了此方法") let formRow = sourceIndexPath.row let toRow = destinationIndexPath.row let formContent = Content[formRow] Content.remove(at: formRow) Content.insert(formContent, at: toRow) } }
import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ var articles = ["A","B"] var Contents = ["1","2"] override func viewDidLoad() { super.viewDidLoad() let tableView = UITableView(frame:self.view.frame) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none self.view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count*2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let idA = "articlesCell" let idB = "ContentsCell" var CellA:UITableViewCell? var CellB:UITableViewCell? if indexPath.row%2 == 0{ CellA = tableView.dequeueReusableCell(withIdentifier: idA) if CellA == nil{ CellA = UITableViewCell(style: .default, reuseIdentifier: idA) } CellA?.textLabel?.text = articles[indexPath.row/2] return CellA! }else{ CellB = tableView.dequeueReusableCell(withIdentifier: idB) if CellB == nil{ CellB = UITableViewCell(style: .default, reuseIdentifier: idB) } CellB?.textLabel?.text = Contents[indexPath.row/2] return CellB! } } }
建立一個自定義swift文件,父類爲UITableViewCell,名稱爲CustomizeTableVIewCell
編輯CustomizeTableViewCell:代理
import UIKit class CustomizeTableViewCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate { var tableView:UITableView! var Content:[String] = [] override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) //進行初始化,後續在進行更改 tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 50)) tableView.dataSource = self tableView.delegate = self //設置是否容許滑動(設爲false,防止內容跟着手指滑動而滑動) tableView.isScrollEnabled = false tableView.separatorStyle = .none self.addSubview(tableView) } //設置單元格數量 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Content.count } //設置單元格內容 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let id = "reusedCell" var cell = tableView.dequeueReusableCell(withIdentifier: id) if cell == nil{ cell = UITableViewCell(style: .default, reuseIdentifier: id) } cell?.textLabel?.text = Content[indexPath.row] cell?.textLabel?.font = UIFont.systemFont(ofSize: 12) cell?.textLabel?.numberOfLines = 0 return cell! } //設置單元格高度 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let ContentNum = Content[indexPath.row] //計算內容高度(ContentSize.width/170計算有多少行文字) let ContentSize = ContentNum.boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil) let cellHeight = ContentSize.height*(ContentSize.width/170) if cellHeight < 30{ return 30 }else{ return cellHeight } } //根據數據源內容來設置UITableView高度(+50防止內容擁擠) func setContentForTable(_ content:[String]){ self.Content = content var tableHeight:CGFloat = 0 for i in 0..<content.count { let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil) tableHeight += ContentSize.height*(ContentSize.width/170) } tableView.frame = CGRect(x: 20, y: 0, width: 300, height: tableHeight + 50) tableView.reloadData() } func getMyHeight()->CGFloat{ return tableView.frame.size.height } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
編輯ViewController:code
import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ var articles = ["徐志摩","克萊兒▪麥克福爾","東野圭吾"] var Contents = [["我是天空裏的一片雲,偶爾投影在你的波心,你沒必要訝異,更無須歡喜,在轉瞬間消滅了蹤跡。你我相逢在黑夜的海上,你有你的,我有個人,方向,你記得也好,最好你忘掉,在這交會時互放的光亮"],["當靈魂休眠的時候,我敢確定它們獲得了片刻的平靜和安寧。111111111111111111111111"],["你我都不可能擺脫時鐘的束縛,彼此都已淪爲社會這個時鐘的齒輪,一旦少了齒輪,時鐘就會出亂子。縱然本身渴望率性而爲,周遭也不允許,咱們雖然獲得了安定,但失去自由也是不爭的事實。"]] override func viewDidLoad() { super.viewDidLoad() let tabView = UITableView(frame:CGRect(x: 0, y: 20, width: self.view.bounds.width, height: self.view.bounds.height)) tabView.delegate = self tabView.dataSource = self tabView.separatorStyle = .none self.view.addSubview(tabView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count*2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let idA = "cellForArticles" let idB = "cellForContent" var cell1:UITableViewCell? var cell2:CustomizeTableViewCell? if indexPath.row%2 == 0{ cell1 = tableView.dequeueReusableCell(withIdentifier: idA) if cell1 == nil{ cell1 = UITableViewCell(style: .default, reuseIdentifier: idA) } cell1?.textLabel?.text = articles[indexPath.row/2] cell1?.textLabel?.textColor = UIColor.gray cell1?.backgroundColor = UIColor.black cell1?.textLabel?.font = UIFont.systemFont(ofSize: 16) return cell1! }else{ cell2 = tableView.dequeueReusableCell(withIdentifier: idB) as? CustomizeTableViewCell if cell2 == nil{ cell2 = CustomizeTableViewCell(style: .default, reuseIdentifier: idB) } let content = Contents[indexPath.row/2] cell2?.setContentForTable(content) return cell2! } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row % 2 == 0{ return 40 }else{ let Content = Contents[indexPath.row/2] var cellHeight:CGFloat = 0 for i in 0..<Content.count{ let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil) cellHeight += ContentSize.height*(ContentSize.width/170) } return cellHeight + 50 } } }
使用scrollToRow方法滾動到最後一行orm
let secon = 1 //最後一個分組的索引(0開始,若是沒有分組則爲0) let rows = 10 //最後一個分組最後一條項目的索引 let indexPath = IndexPath(row: rows, section: secon) self.tableView?.scrollToRow(at: indexPath, at:.bottom, animated: true)
使用setContentOffset設置偏移量實現滾動:索引
let offset = CGPoint(x:0, y:self.tableView!.contentSize.height - self.tableView!.bounds.size.height) self.tableView!.setContentOffset(offset, animated: true)