且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Swift在UITableview中加载自定义单元格(Xib)

更新时间:2022-12-28 16:41:17

import UIKit
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //MARK:- Sample Data Array to load in TableView
        let sampleArrray: \[String\] = \["val1", "val2", "val3", "val4", "val5"]

    //MARK:- Cell reuse identifier 
        let cellReuseIdentifier = "cell"


    //MARK:- UITableView outlet 
         @IBOutlet var tableView: UITableView!

          override func viewDidLoad() {
            super.viewDidLoad()

            // Registering the custom cell

            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

            // Setting delegate and Datasourse as same viewcontroller (this code is not neccessory if we are setting it from storyboard)

            tableView.delegate = self
            tableView.dataSource = self
        }
    //UITableview required methods 

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return sampleArrray.count
        }

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

            cell.textLabel?.text = sampleArrray\[indexPath.row\]

            return cell
        }

        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
           print("clicked at: \(indexPath.row)")
           //Here u can get the selected cell and add action related to this cell seelction 
        }

添加了用于设置数据源和故事板委托的屏幕截图

Added Screenshot for setting Datasource and delegate from storyboard