Swift iOS : 定製Cell

RecoReco發表於2019-02-11

TableViewCell提供了種種定製的可能,包括textLabel,detailLabel,各種訪問附件等。但是需要死記硬背,何必呢,反正一個繼承了UITableViewCell的子類,然後在其內加入自己的定製View其實並不複雜,並且使用了同樣的加入subView的方案。因此,我常常更加傾向於使用這樣的類。因為更加通用,並且更加靈活,因為,你想要的任何檢視和它們自己組合的佈局,都是可以自由定義的。

如下案例,就是一個使用繼承子類方案的TableView:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let page = Page()
        page.view.backgroundColor = .blue
        self.window!.rootViewController = page
        self.window?.makeKeyAndVisible()
        return true
    }
}
class Table: UITableView,UITableViewDataSource{
    let arr = ["Long text Long text 
Long text Long text Long text Long text Long text Long text Long text ","delphi"]
    let MyIdentifier = "cell"
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame:frame,style:style)
        self.dataSource = self
        self.register(Cell.self, forCellReuseIdentifier: MyIdentifier)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let a = tableView.dequeueReusableCell(withIdentifier: MyIdentifier) as! Cell
        a.view1.text = String(arr[indexPath.row])
        return a
    }
}
class Cell : UITableViewCell{
    var view1  = UILabel()
    override func layoutSubviews() {
        self.contentView.addSubview(view1)
        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        view1.translatesAutoresizingMaskIntoConstraints = false
        let views = ["view1":view1]
        let hConstraint=NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view1]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        self.contentView.addConstraints(hConstraint)
        let vConstraint=NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view1]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        self.contentView.addConstraints(vConstraint)
    }
}
class Page: UIViewController {
    var a : Table!
    override func viewDidLoad() {
        super.viewDidLoad()
        a  = Table()
        a.frame = CGRect(x: 0,y: 30,width: 300,height: 400)
        self.view.addSubview(a)
        a.estimatedRowHeight = 44.0
        a.rowHeight = UITableViewAutomaticDimension
    }
}複製程式碼

相關文章