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

How to load Custom cell (Xib) in UITableview using Swift

这是我的代码

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{
    return 10   
}

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

    bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
    //NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell

    cell = blucell
    devname.text = peri[indexPath.row]
    devstrength.text = signalstrength[indexPath.row]

    bluetoothlog.backgroundColor = UIColor.clearColor()
    return cell        
}

我已经尝试过上面的代码,但在 Tableview 中没有显示任何内容,请帮助我更改此代码工作

谢谢

你的函数 registerNib ,你尝试在 viewDidLoad() 方法中编写并从 cellForRowAtIndexPah 中删除,然后测试你的项目

您的 Cell 实例应该是 CustomCell 实例而不是 UITableView Cell。 var cell :UITableViewCell 应该替换为 可变单元格:devicedet

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

    var cell :devicedet = tableView.dequeueReusableCellWithIdentifier("discovered") as UITableViewCell!

    bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
    //NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell

    cell = blucell
    devname.text = peri[indexPath.row]
    devstrength.text = signalstrength[indexPath.row]

    bluetoothlog.backgroundColor = UIColor.clearColor()
    return cell        
}
  • 命令 registerNib 应该在 ViewDidLoad 中调用,而不是在行的每个单元格调用中调用
  • 什么是'bluecell'?在你的回调 cellforTable.. 中,你分配 cell = blucell -> 这可能会导致你的问题。

试试这个:

import UIKit

class YourViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

override func viewDidLoad() {
        super.viewDidLoad()

//call register nib here!!
        bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
    }

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

//it seem that you have to add a è
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
{
    let cell :UITableViewCell = tableView.dequeueReusableCellWithIdentifier("discovered") as UITableViewCell!
/*  REMOVE THIS
    bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
    //NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell
*/
  //// THEN, UPDATE YOUR CELL with YOUR DATAs

/* I don't understand what are you doing with this line of code:
    cell = blucell

*/

    devname.text = peri[indexPath.row]
    devstrength.text = signalstrength[indexPath.row]

//Seem that bluetoothlog is the tableview, you should call it in viewdidload or viewwillappear()
    bluetoothlog.backgroundColor = UIColor.clearColor()

    return cell        
}

}
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 
        }

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

在viewDidLoad中注册XIB如下图

var userDetailsNIB = UINib(nibName: "UserDetailsCell", bundle: nil)
        viewListingTable.registerNib(userDetailsNIB, forCellReuseIdentifier: "UserDetailsViewCellID")

And in func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

function use it by access it with Identifier which created in viewDidLoad method

let cell = tableView.dequeueReusableCellWithIdentifier("UserDetailsViewCellID") as UserDetailsViewCell

return cell

如果您想在 swift 的 UITableView 中加载自定义单元格 (Xib),您可以使用以下代码。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count; //This function returns number of rows in table view
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:YourTableViewCell! = tableView.dequeueReusableCellWithIdentifier("YourTableViewCell", forIndexPath:indexPath)as! YourTableViewCell
   // Do additional code here
}

别忘了在viewDidLoad中注册nib

override func viewDidLoad() {
    super.viewDidLoad()
    // registering your nib
    let yourNibName = UINib(nibName: "YourTableViewCell", bundle: nil)
    tableView.registerNib(yourNibName, forCellReuseIdentifier: "YourTableViewCell")
    // Do any additional setup after loading the view.
}
  1. 使用重用标识符注册您的 NIB:

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "Cell")
    }
    
  2. 然后您的 cellForRowAtIndexPath 将实例化单元格。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! devicedet
    
        return cell
    }
    

在 Swift

中注册 xib 单元格
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UINib(nibName: "XibCell", bundle: nil), forCellReuseIdentifier: "Cell")
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell
    return cell
}

我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
     tableView.register(
         UINib(nibName: "XibCell", bundle: nil), 
         forCellReuseIdentifier: "Cell"
     )
 }

func tableView(_ tableView: UITableView, 
               cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") 
    return cell as! UITableViewCell
}