Swift4.x普通ノート03 Cellをカスタマイズし、TableView Cellを拡張してCell呼び出しを簡略化する方法
3475 ワード
まずmvcのviewフォルダにMyCellを定義し、
UITableViewCellを継承し、
選択した言語はSwift
そしてコントローラで使えるようになり、
以下はコードです.ここのコントローラは次のとおりです.
登録が終わったら、システムの方法を置き換えることができます.コードは以下の通りです.
次にcell呼び出しを簡略化し、次の手順に従います.
1,私達の主要なフォルダの中で新しいUIView+Extension.swift
2.同級ディレクトリの下にUItableView+Extensionを新規作成する.swift、ここに広がっているのはUItableViewです
2歩で、複雑ではありません.
次は置換です.
使うときも差し替えて
これで終わりですが、まとめてみると、カスタムcellの使用実戦です.
UITableViewCellを継承し、
選択した言語はSwift
そしてコントローラで使えるようになり、
以下はコードです.ここのコントローラは次のとおりです.
class MineViewController: UITableViewController{
.....
override func viewDidLoad() {
super.viewDidLoad()
// Cell
tableView.register(UINib(nibName: String(describing:MyCell.self), bundle: nil), forCellReuseIdentifier: String(describing:MyCell.self))
}
.....
}
登録が終わったら、システムの方法を置き換えることができます.コードは以下の通りです.
class MineViewController: UITableViewController{
.....
// cell 。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeueReusableCell, cell
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing:MyCell.self)) as! MyCell
// ,
let section = sections[indexPath.section]
let myCellModel = section[indexPath.row]
// leftLabel xib label,
cell.leftLabel.text = myCellModel.text
// rightLabel xib label,
cell.rightLabel.text = myCellModel.grey_text
// cell
return cell
}
.....
}
次にcell呼び出しを簡略化し、次の手順に従います.
1,私達の主要なフォルダの中で新しいUIView+Extension.swift
import UIKit
protocol RegisterCellOrNib {}
extension RegisterCellOrNib{
static var identifier:String{
return "\(self)"
}
static var nib:UINib?{
return UINib(nibName: "\(self)", bundle: nil)
}
}
2.同級ディレクトリの下にUItableView+Extensionを新規作成する.swift、ここに広がっているのはUItableViewです
import UIKit
extension UITableView{
//
func fp_registerCell(cell:T.Type) where T:RegisterCellOrNib {
if let nib = T.nib {
register(nib, forCellReuseIdentifier: T.identifier)
}else{
register(cell, forCellReuseIdentifier: T.identifier)
}
}
// cell
func fp_dequeueReusableCell(indexPath:IndexPath) -> T where T:RegisterCellOrNib {
return dequeueReusableCell(withIdentifier: T.identifier,for: indexPath)as! T
}
}
2歩で、複雑ではありません.
次は置換です.
class MineViewController: UITableViewController{
.....
override func viewDidLoad() {
super.viewDidLoad()
// Cell
tableView.register(UINib(nibName: String(describing:MyCell.self), bundle: nil), forCellReuseIdentifier: String(describing:MyCell.self))
//
tableView.fp_registerCell(cell: MyCell.self)
}
}
使うときも差し替えて
class MineViewController: UITableViewController{
.....
// cell 。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeueReusableCell, cell
//let cell = tableView.dequeueReusableCell(withIdentifier: String(describing:MyCell.self)) as! MyCell
//
let cell = tableView.fp_dequeueReusableCell(indexPath: indexPath) as MyCell
......
return cell
}
.....
}
これで終わりですが、まとめてみると、カスタムcellの使用実戦です.