无法使用标识符Cell将单元格出列 - 必须为标识符注册nib或类,或者在故事板中连接原型单元格

问题描述 投票:88回答:15

我对编码很新,对Xcode(Swift)来说真的很新。我知道我需要注册一个笔尖或一个班级,但我不明白'在哪里或如何?'。

import UIKit

class NotesListViewController: UITableViewController {

    @IBOutlet weak var menuButton: UIBarButtonItem!

  override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self,
      selector: "preferredContentSizeChanged:",
      name: UIContentSizeCategoryDidChangeNotification,
      object: nil)

    // Side Menu

    if self.revealViewController() != nil {
        menuButton.target = self.revealViewController()
        menuButton.action = "revealToggle:"
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

  }

  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    // whenever this view controller appears, reload the table. This allows it to reflect any changes
    // made whilst editing notes
    tableView.reloadData()
  }

  func preferredContentSizeChanged(notification: NSNotification) {
    tableView.reloadData()
  }

  // #pragma mark - Table view data source

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
  }

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

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

    let note = notes[indexPath.row]
    let font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
    let textColor = UIColor(red: 0.175, green: 0.458, blue: 0.831, alpha: 1)
    let attributes = [
      NSForegroundColorAttributeName : textColor,
      NSFontAttributeName : font,
      NSTextEffectAttributeName : NSTextEffectLetterpressStyle
    ]
    let attributedString = NSAttributedString(string: note.title, attributes: attributes)

    cell.textLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)

    cell.textLabel?.attributedText = attributedString

    return cell
  }

  let label: UILabel = {
    let temporaryLabel = UILabel(frame: CGRect(x: 0, y: 0, width: Int.max, height: Int.max))
    temporaryLabel.text = "test"
    return temporaryLabel
    }()

  override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
    label.sizeToFit()
    return label.frame.height * 1.7
  }

  override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
      notes.removeAtIndex(indexPath.row)
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
  }

  // #pragma mark - Navigation

  // In a storyboard-based application, you will often want to do a little preparation before navigation
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if let editorVC = segue.destinationViewController as? NoteEditorViewController {

      if "CellSelected" == segue.identifier {
        if let path = tableView.indexPathForSelectedRow() {
          editorVC.note = notes[path.row]
        }
      } else if "AddNewNote" == segue.identifier {
        let note = Note(text: " ")
        editorVC.note = note
        notes.append(note)
      }
    }
  }

}
ios swift iphone xcode6
15个回答
62
投票

您是否在故事板中将表格单元格标识符设置为“单元格”?

或者您是否已将UITableViewController的课程设置为该场景中的班级?


1
投票

我有同样的问题。这个问题对我有用。在故事板中选择您的表格视图并将其从静态单元格更改为动态单元格。


1
投票

如果您通过Interface Builder定义了单元格,可以在UICollectionViewUITableView中放置一个单元格:

确保您使用您创建的实际类绑定了单元格,并且非常重要,您选中了“从目标继承模块”


0
投票

对于那些决定拥有多个单元格和不同xib文件的iOS好友(比如我),解决方案不是要有标识符,而是要做到这一点:

let cell = Bundle.main.loadNibNamed("newsDetails", owner: self, options: nil)?.first as! newsDetailsTableViewCell

这里newsDetails是xib文件名。


0
投票

斯威夫特5

您需要使用UINib方法在viewDidLoad中注册单元格

override func viewDidLoad() 
{
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    //register table view cell        
    tableView.register(UINib.init(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
}

0
投票

它曾经用于swift 3和swift 4,但现在它无法工作。

喜欢

self.tableView.register(MyTestTableViewCell.self, forCellReuseIdentifier: "cell")

所以我在swift 5中尝试了上面提到的大多数解决方案,但没有得到任何运气。

最后我尝试了这个解决方案,它对我有用。

override func viewDidLoad() 
{

    tableView.register(UINib.init(nibName: "MyTestTableViewCell", bundle: nil), forCellReuseIdentifier: "myTestTableViewCell")
}

0
投票

我的问题是我在异步注册调度队列中的表视图单元格。如果您在故事板中注册了表视图源和委托引用,则调度队列将延迟单元的注册,因为名称表明它将异步发生并且您的表视图正在查找单元。

DispatchQueue.main.async {
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

您不应该使用调度队列进行注册或执行此操作:

DispatchQueue.main.async {
    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

89
投票

你可以为你的UITableViewCell注册一个类:

使用Swift 3+:

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

使用Swift 2.2:

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

确保在故事板的cell中也复制了相同的标识符“UITableViewCell”。

self”是让课程使用类名,然后是.self


26
投票

这对我有用,也可以帮助你:

Swift 4+:

self.tableView.register(UITableViewCell.self, forCellWithReuseIdentifier: "cell")

斯威夫特3:

self.tableView.register(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")

Swift 2.2:

self.tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")

我们必须将Identifier属性设置为Table View Cell,如下图所示,

enter image description here


23
投票

今天我遇到了这个问题,通过选择Product - > Clean解决了这个问题。因为我的代码是正确的,所以我很困惑。问题从使用命令-Z开始太多次了:)


17
投票

我的情况我通过在Table View Cell的“Identifier”属性中命名它来解决这个问题:

enter image description here

不要忘记:在你的类中声明:UITableViewDataSource

 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell

8
投票

只需拖动一个单元格(就像你为TableViewController所做的那样)并通过释放TableViewController上的单元格来添加它。单击单元格并转到其属性检查器并将其标识符设置为“单元格”。希望它可以工作。


不要忘记在Attributes Inspector上想要标识符。

(不是“身份检查员”中的“恢复身份证”!)


6
投票

这个问题发生的另一个原因是早期的问题。在显示新的ViewController时,直接实例化目标ViewController当然不会从StoryBoard加载原型单元格。正确的解决方案应该始终是通过故事板实例化视图控制器,如下所示:

storyboard?.instantiateViewController(withIdentifier: "some_identifier")

3
投票

在Swift 3.0中,为您的UITableViewCell注册一个类,如下所示:

tableView.register(UINib(nibName: "YourCellXibName", bundle: nil), forCellReuseIdentifier: "Cell")

1
投票

我刚刚遇到同样的问题,看到这篇文章。对我来说,这是因为我忘了设置单元格的标识符,也像其他答案中提到的那样。我想说的是,如果您使用故事板加载自定义单元格,我们不需要在代码中注册表格视图单元格,这可能会导致其他问题。

有关详细信息,请参阅此帖

Custom table view cell: IBOutlet label is nil

© www.soinside.com 2019 - 2024. All rights reserved.