从Swift中的nib定制UITableViewCell

Isu*_*uru 128 uitableview ios swift ios8

我正在尝试从笔尖创建自定义表格视图单元格.我在这里指的是这篇文章.我面临两个问题.

我创建了一个.xib文件,其中拖动了一个UITableViewCell对象.我创建了一个子类,UITableViewCell并将其设置为单元格的类,将Cell设置为可重用的标识符.

import UIKit

class CustomOneCell: UITableViewCell {

    @IBOutlet weak var middleLabel: UILabel!
    @IBOutlet weak var leftLabel: UILabel!
    @IBOutlet weak var rightLabel: UILabel!

    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
Run Code Online (Sandbox Code Playgroud)

在UITableViewController中我有这个代码,

import UIKit

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

    var items = ["Item 1", "Item2", "Item3", "Item4"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let identifier = "Cell"
        var cell: CustomOneCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell
        if cell == nil {
            tableView.registerNib(UINib(nibName: "CustomCellOne", bundle: nil), forCellReuseIdentifier: identifier)
            cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell
        }

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码没有错误,但是当我在模拟器中运行它时,它看起来像这样.

在此输入图像描述

在故事板中的UITableViewController中,我没有对单元格做任何事情.空标识符,没有子类.我尝试将Cell标识符添加到原型单元格并再次运行但我得到相同的结果.

我遇到的另一个错误是,当我尝试在UITableViewController中实现以下方法时.

override func tableView(tableView: UITableView!, willDisplayCell cell: CustomOneCell!, forRowAtIndexPath indexPath: NSIndexPath!) {

    cell.middleLabel.text = items[indexPath.row]
    cell.leftLabel.text = items[indexPath.row]
    cell.rightLabel.text = items[indexPath.row]
}
Run Code Online (Sandbox Code Playgroud)

如我在文章中所提到的,我将cell参数的类型形式UITableViewCell更改CustomOneCell为我的UITableViewCell的子类.但我得到以下错误,

使用选择器'tableView重写方法:willDisplayCell:forRowAtIndexPath:'具有不兼容的类型'(UITableView!,CustomOneCell!,NSIndexPath!) - >()'

任何人都知道如何解决这些错误?这些似乎在Objective-C中运行良好.

谢谢.

编辑:我刚注意到,如果我将模拟器的方向更改为横向并将其转回肖像,则单元格会出现!我仍然无法弄清楚发生了什么.我在这里上传了一个Xcode项目,如果你有时间快速浏览就可以证明这个问题.

Ima*_*tit 194

您应该为您的项目尝试以下代码:( Swift 3+的语法)

CustomOneCell.swift

import UIKit

class CustomCell: UITableViewCell {

    // Link those IBOutlets with the UILabels in your .XIB file
    @IBOutlet weak var middleLabel: UILabel!
    @IBOutlet weak var leftLabel: UILabel!
    @IBOutlet weak var rightLabel: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

TableViewController.swift

import UIKit

class TableViewController: UITableViewController {

    let items = ["Item 1", "Item2", "Item3", "Item4"]

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

    // MARK: - UITableViewDataSource

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

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

        cell.middleLabel.text = items[indexPath.row]
        cell.leftLabel.text = items[indexPath.row]
        cell.rightLabel.text = items[indexPath.row]

        return cell
    }

}
Run Code Online (Sandbox Code Playgroud)

下图显示了一组约束,这些约束与提供的代码一起使用,而没有来自Xcode的任何约束歧义消息.

在此输入图像描述

  • 感谢您的回复。但这也不起作用。我需要更改表视图控制器中的任何内容吗?因为它仍然设置为原型单元格。 (2认同)
  • @KirillKudaev 它没有在 Swift 4 中重命名,但在 Swift 3 中:我已经修复了您的编辑。 (2认同)

int*_*ico 27

这是我使用Swift 2和Xcode 7.3的方法.此示例将使用单个ViewController加载两个.xib文件 - 一个用于UITableView,另一个用于UITableCellView.

在此输入图像描述

对于此示例,您可以将UITableView权限放入空的TableNib .xib文件中.在里面,将文件的所有者设置为ViewController类,并使用插座引用tableView.

在此输入图像描述

在此输入图像描述

现在,在视图控制器中,您可以像往常一样委托tableView,就像这样

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...
Run Code Online (Sandbox Code Playgroud)

要再次创建自定义单元格,请将Table View Cell对象拖放到空的TableCellNib .xib文件中.这次,在单元格.xib文件中,您不必指定"所有者",但您需要指定自定义类标识符,如"TableCellId"

在此输入图像描述 在此输入图像描述

使用您需要的任何插件创建您的子类

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

最后......回到View Controller中,您可以加载并显示整个事物

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}
Run Code Online (Sandbox Code Playgroud)

代码显示了如何简单地加载和显示nib文件(表),以及如何注册nib以供单元使用.

希望这可以帮助!!!

  • 你能解释一下这一行中的“tableCellId”是什么.... self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId .... 因为你还没有定义那是什么。并且您不能在 xib 中手动定义标识符 .. 没有选项可以定义它 (2认同)

Gur*_*ngh 13

斯威夫特4

注册Nib

tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")
Run Code Online (Sandbox Code Playgroud)

在TableView DataSource中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
          return cell
    }
Run Code Online (Sandbox Code Playgroud)


Der*_*ike 12

带截图的详细解决方案

  1. 创建一个空的用户界面文件并将其命名为MyCustomCell.xib.

在此处输入图片说明

  1. 添加 aUITableViewCell作为您的 xib 文件和您想要的任何其他可视组件的根目录。

在此处输入图片说明

  1. 创建一个可可触摸类文件,类名MyCustomCell作为UITableViewCell.

在此处输入图片说明 在此处输入图片说明

  1. 为您的自定义表格视图单元格设置自定义类和重用标识符。

在此处输入图片说明 在此处输入图片说明

  1. 打开辅助编辑器并ctrl+drag为您的可视组件创建插座。

在此处输入图片说明

  1. 配置 aUIViewController以使用您的自定义单元格。
class MyViewController: UIViewController {

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad {
        super.viewDidLoad()

        let nib = UINib(nibName: "MyCustomCell", bundle: nil)
        myTable.register(nib, forCellReuseIdentifier: "MyCustomCell")
        myTable.dataSource = self
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell") as? MyCustomCell {
            cell.myLabel.text = "Hello world."
            return cell
        }
        ...
    }
}

Run Code Online (Sandbox Code Playgroud)


小智 6

迅速4.1.2

xib。

创建 ImageCell2.swift

步骤1

import UIKit

class ImageCell2: UITableViewCell {

    @IBOutlet weak var imgBookLogo: UIImageView!
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblPublisher: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}
Run Code Online (Sandbox Code Playgroud)

第2步 。根据Viewcontroller类

  import UIKit

    class ImageListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tblMainVC: UITableView!

    var arrBook : [BookItem] = [BookItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
         //Regester Cell
        self.tblMainVC.register(UINib.init(nibName: "ImageCell2", bundle: nil), forCellReuseIdentifier: "ImageCell2")
        // Response Call adn Disply Record
        APIManagerData._APIManagerInstance.getAPIBook { (itemInstance) in
            self.arrBook = itemInstance.arrItem!
            self.tblMainVC.reloadData()
        }
    }
    //MARK: DataSource & delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrBook.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//    [enter image description here][2]
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ImageCell2") as! ImageCell2
        cell.lblTitle.text = self.arrBook[indexPath.row].title
        cell.lblPublisher.text = self.arrBook[indexPath.row].publisher
        if let authors = self.arrBook[indexPath.row].author {
            for item in authors{
                print(" item \(item)")
            }
        }
        let  url  = self.arrBook[indexPath.row].imageURL
        if url == nil {
            cell.imgBookLogo.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "download.jpeg"))
        }
        else{
            cell.imgBookLogo.kf.setImage(with: URL(string: url!)!, placeholder: UIImage.init(named: "download.jpeg"))
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    } 

}
Run Code Online (Sandbox Code Playgroud)


小智 5

您没有按照以下方式注册您的笔尖:

tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
Run Code Online (Sandbox Code Playgroud)