2016-07-28 4 views
0

Я недавно начал программировать с помощью быстрого (быстрого новичку: б) получил ошибку и не имеет ни малейшего представления о том, как это исправить: сSwift «не удались из очереди ячейки с идентификатором intervalCellIdentifier

это код ViewController .swift!

import UIKit 

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDataSource,UITableViewDelegate { 

@IBOutlet weak var picker1: UIPickerView! 
@IBOutlet weak var keySelect: UITableView! 

var Array = ["2", "3", "4"] 

@IBOutlet weak var picker1label: UILabel! 

@IBOutlet weak var keyselectView: UILabel! 
@IBOutlet weak var keylabel: UIButton! 

let intervalCellIdentifier = "intervalCellIdentifier" 

var intervalNames = ["Q", "W", "E", "R", "T", "Y"] 

let limit = 5 

var answer1 = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 

    picker1.delegate = self 
    picker1.dataSource = self 

    //edited 
    keySelect.delegate = self 
    keySelect.dataSource = self 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 




func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { 

    return Array[row] 

} 

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { 
    return Array.count 
} 


func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { 
    return 1 
} 

@IBAction func submit1(sender: AnyObject) { 

    if(answer1 == 0) { 
     picker1label.text = "2" 
    } 

    else if(answer1 == 1) { 
     picker1label.text = "3" 
    } 

    else { 
     picker1label.text = "4" 
    } 

} 

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 

    answer1 = row 
} 

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


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

    cell.accessoryType = .None 
    cell.textLabel?.text = intervalNames[indexPath.row] 

    return cell 
} 



//MARK: - UITableViewDelegate 


func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { 

    if let sr = tableView.indexPathsForSelectedRows { 
     if sr.count == limit { 
      let alertController = UIAlertController(title: "Oops", message: 
        "You are limited to \(limit) selections", preferredStyle: .Alert) 
      alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: {action in 
       })) 
      self.presentViewController(alertController, animated: true, completion: nil) 

      return nil 
     } 
    } 

    return indexPath 
} 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    print("selected \(intervalNames[indexPath.row])") 

    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
     if cell.selected { 
      cell.accessoryType = .Checkmark 
     } 
    } 

    if let sr = tableView.indexPathsForSelectedRows { 
     print("didDeselectRowAtIndexPath selected rows:\(sr)") 
    } 
} 

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 

    print("deselected \(intervalNames[indexPath.row])") 

    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
     cell.accessoryType = .None 
    } 

    if let sr = tableView.indexPathsForSelectedRows { 
     print("didDeselectRowAtIndexPath selected rows:\(sr)") 
    } 
} 

} 

2016-07-28 23: 08: 29,868 customkeyboard [60865: 1611607] * Отказ Утверждение в - [UITableView dequeueReusableCellWithIdentifier: forIndexPath:], /BuildRoot/Library/Caches/com.apple. xbs/Источники/UIKit_Sim/UIKit-3512.29.5/UITitView.m: 6547 2016-07-28 23: 08: 29.945 customkeyboard [60865: 1611607] * Завершение приложения из-за неотображенного исключения «NSInternalInconsistencyException», причина: «не удалось для деактивации ячейки с идентификатором intervalCellIdentifier - необходимо зарегистрировать ниб или класс для идентификатора или подключить прототип ячейки в раскадровке '

это ошибка Объяснение

помочь мне (?): 3

+0

Вы используете прототип ячейки или отдельный xib? –

+0

Возможный дубликат [Утверждение об ошибке в dequeueReusableCellWithIdentifier: forIndexPath:] (http://stackoverflow.com/questions/12737860/assertion-failure-in-dequeuereusablecellwithidentifierforindexpath) – benuuu

+0

спасибо за все комментарии! исправил его и забыл ответить; <3 –

ответ

2

1. XIB файл

Вы должны зарегистрировать ячейку таблицы первой, может быть в viewDidLoad, как:

let nib = UINib(nibName: "CustomCell", bundle: NSBundle.mainBundle()) 
tableView.registerNib(nib, forCellReuseIdentifier: "CustomCellIdentifier") 

Это применимо, если мы используем пользовательскую ячейку .xib файл.

2. Без XIB файла

А вот это решение, если мы не создаем отдельный .xib файл для пользовательской ячейки:

Нам нужно создать динамический прототип ячейки в табличном виде: enter image description here

Тогда мы должны обеспечить имя класса и идентификатор повторного использования для нашей пользовательской ячейки как: enter image description here

enter image description here Здесь не нужно регистрировать класс или ниб!


Вот cellForRowAtIndexPath реализация:

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

    // Configure the cell... 
    let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCellId", forIndexPath: indexPath) as! CustomTableViewCell 
    cell.setCellIndexLabel(indexPath.row) 

    return cell 
} 

Эта реализация будет одинакова для обоих указанных выше решений.


3.Только реализация класса
Без XIB, без Dynamic Prototype

Здесь обычай клетки без XIB или Dynamic Prototype:

class WithoutNibCustomTableViewCell: UITableViewCell { 

override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
    //do custom initialisation here, if any 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

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 
} 

class func identifier() -> String { 
    return "WithoutNibCustomTableViewCellId" 
} 

//MARK: Public Methods 
func setCellIndexLabel(index: Int) { 
    let customLbl = UILabel(frame: CGRectMake(0, 0, 100, 40)) 
    customLbl.text = String(index) 
    contentView.addSubview(customLbl) 
} 

}

Затем, в виде таблицы, мы должны зарегистрировать клетку класс как:

tableView!.registerClass(WithoutNibCustomTableViewCell.classForCoder(), forCellReuseIdentifier: WithoutNibCustomTableViewCell.identifier()) 

cellForRowAtIndexPath также такие же как выше, как:

let cell = tableView.dequeueReusableCellWithIdentifier(WithoutNibCustomTableViewCell.identifier(), forIndexPath: indexPath) as! WithoutNibCustomTableViewCell 
    cell.setCellIndexLabel(indexPath.row) 
    return cell 
+1

Пожалуйста, покройте все случаи, предоставив случай, когда ячейка определена в коде, а не в .xib-файле –

+0

Предоставлено решение для обоих случаев, пользовательская ячейка с файлом '.xib' и без него! – D4ttatraya

+0

Без .xib - просто в коде, я имею в виду, с registerClass, но работа вы сделали. Произвести впечатление =) –

0

в cellForRow изменить: пусть клеток = tableView.dequeueReusableCellWithIdentifier (intervalCellIdentifier, forIndexPath: indexPath) в UITableViewCell по пусть клетка = tableView.dequeueReusableCellWithIdentifier (intervalCellIdentifier, forIndexPath: indexPath) как имя вашего класса ячейки.

+0

спасибо! был полезен –

0

я опубликовал стручок, который сделает вашу жизнь проще, работая с клетками:

https://cocoapods.org/pods/CellRegistration

Это упрощает API только одна линия:

let : MyCustomCell = tableView.dequeueReusableCell(forIndexPath: indexPath) 
Смежные вопросы