Мой TapCell1.Swift
Это Custom UITableViewCell View
import UIKit
class TapCell1: UITableViewCell
{
@IBOutlet var labelText : UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
println("Ente")
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
}
}
Мой ViewController.Swift
Все источники данных и делегаты установлены правильно. Но моя пользовательская ячейка не отображается.
import UIKit
class NextViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
@IBOutlet var label: UILabel
@IBOutlet var tableView : UITableView
var getvalue = NSString()
override func viewDidLoad()
{
super.viewDidLoad()
label.text="HELLO GOLD"
println("hello : \(getvalue)")
self.tableView.registerClass(TapCell1.self, forCellReuseIdentifier: "Cell")
}
func tableView(tableView:UITableView!, numberOfRowsInSection section:Int)->Int
{
return 5
}
func numberOfSectionsInTableView(tableView:UITableView!)->Int
{
return 1
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TapCell1
cell.labelText.text="Cell Text"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Проблема в том, что Моя пользовательская ячейка не отображается. Пожалуйста, предложите что-нибудь, что я сделал не так.
Примечание: вот мой код ссылка на скачивание моего файла
Я наконец сделал это.
Для TapCell1.Swift
import UIKit
class TapCell1: UITableViewCell {
@IBOutlet var labelTitle: UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}
}
Для NextViewController.Swift
import UIKit
class NextViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView
var ListArray=NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
let nibName = UINib(nibName: "TapCell1", bundle:nil)
self.tableView.registerNib(nibName, forCellReuseIdentifier: "Cell")
for i in 0...70 {
ListArray .addObject("Content: \(i)")
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)->Int {
return ListArray.count
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 51
}
func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TapCell1
//cell.titleLabel.text = "\(ListArray.objectAtIndex(indexPath.item))"
cell.labelTitle.text = "\(ListArray.objectAtIndex(indexPath.row))"
return cell
}
}
Моя рабочая кодовая ссылка: CUSTOMIZED TABLE
Вы должны зарегистрировать class
для ячейки. Для этого сделайте Измените эту строку кода на
self.tableView.registerClass(TapCell1.classForCoder(), forCellReuseIdentifier: "Cell")
Правка
Вы код выглядит хорошо, я проверил
//cell.labelText.text="Cell Text"
cell.textLabel.text="Cell Text" // use like this
Решение, скорее всего, определено для установки высоты ячейки вручную:
override func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat
{
return 44
}
Я считаю, что это ошибка Xcode beta 6.
Теперь я смог заставить Custom UITableViewCell работать.
Работает на Xcode 6 beta 5
iOS - это 7.1
Делая это таким образом, вам не нужно регистрировать класс/перо и т.д.
Это моя обычная клетка.
import UIKit class TestCell: UITableViewCell { @IBOutlet var titleImageView: UIImageView! @IBOutlet var titleLabel: UILabel! переопределить init (стиль: UITableViewCellStyle, reuseIdentifier: String!) { super.init (style: style, reuseIdentifier: reuseIdentifier) } переопределить функцию awakeFromNib () { super.awakeFromNib () // Код инициализации } требуется init (кодировщик aDecoder: NSCoder) { super.init (кодер: aDecoder) } }
По вашему мнению, или где бы вы ни расширили «UITableViewDataSource» . Убедитесь, что «cell2» совпадает с «Identifier», который вы дали ему через раскадровку.
func tableView (tableView: UITableView !, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell: TestCell = tableView.dequeueReusableCellWithIdentifier ("cell2", forIndexPath: indexPath) как TestCell // Пример использования пользовательских элементов . cell.titleLabel.text = self.items [indexPath.row] var topImage = UIImage (named: "fv.png") cell.titleImageView.image = topImage возвратная ячейка }
Попробуйте следующий код
var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as CustomTableViewCell
Если вы не используете Storyboard, то создайте новый файл в качестве подкласса UITableViewCell, установите флажок «также создавать файлы XIB», после чего установите свою пользовательскую ячейку. И вот код для просмотра таблицы
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var customcell:CustomTableViewCellClass? = tableView.dequeueReusableCellWithIdentifier("cell") as? CustomTableViewCellClass
if (customcell==nil)
{
var nib:NSArray=NSBundle.mainBundle().loadNibNamed("CustomTableViewCellClass", owner: self, options: nil)
customcell = nib.objectAtIndex(0) as? CustomTableViewCell
}
return customcell!
}
Попробуйте следующий код:
var cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellTableView") as? CustomCellTableView
Проверьте свою историю Story выберите ячейку и посмотрите на «инспектор личности в этом выберите CLASS введите ваш CustomClass и MODULE введите имя вашего проекта
Я сделал это, это прекрасно работает, попробуйте этот совет, чтобы избежать ошибки, чтобы увидеть ниже изображение и код
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
// let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
// cell.textLabel.text = array[indexPath!.row] as String
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell
cell.nameLabel.text = array[indexPath!.row] as String
cell.RestaurentView.image = UIImage(named:images[indexPath!.row])
return cell
}