Подтвердить что ты не робот

UITableView с использованием Swift

Мой TapCell1.swift

Это пользовательский 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.
        }
}

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

Примечание: вот мой код Ссылка на мой файл загрузки

4b9b3361

Ответ 1

Я, наконец, сделал это.

Для 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
    }
}

Ссылка на мой рабочий код: ТАБЛИЦА ТАБЛИЦЫ

Ответ 2

Вы должны зарегистрировать class для ячейки. Для этого измените эту строку кода на

self.tableView.registerClass(TapCell1.classForCoder(), forCellReuseIdentifier: "Cell")

Изменить

Вы правильно выглядите, я проверил его

//cell.labelText.text="Cell Text"

cell.textLabel.text="Cell Text"   // use like this

Ответ 3

Решение, скорее всего, предназначено для установки высоты ячейки вручную как таковой:

override func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat
{
    return 44
}

Я считаю, что это ошибка Xcode beta 6.

Ответ 4

Теперь мне удалось заставить Custom UITableViewCell работать.

Работает на

  • Работает на Xcode 6 beta 6
  • Работает на Xcode 6 beta 5

  • iOS - это 7.1

Как

  • Я создал файл ".xib" для ячейки.
  • Я копирую его в раскадровку.
  • Через раскадровку я даю ей идентификатор.
  • Я убеждаюсь, что это дочерний дочерний элемент tableview

Выполняя это, вам не нужно регистрировать класс /nib и т.д.

Это моя пользовательская ячейка.

import UIKit

class TestCell: UITableViewCell {

    @IBOutlet var titleImageView: UIImageView!
    @IBOutlet var titleLabel: UILabel!

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

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

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

По вашему мнению, или где бы вы ни расширили "UITableViewDataSource". Убедитесь, что "cell2" совпадает с "Идентификатором", который вы дали ему через раскадровку.

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

    var cell:TestCell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as TestCell

    // Example of using the custom elements.
    cell.titleLabel.text = self.items[indexPath.row]

    var topImage = UIImage(named: "fv.png")
    cell.titleImageView.image = topImage

    return cell
}

Ответ 5

Проверьте, что ваша панель "История" выбирает ячейку и просматривает "инспектор идентичности" в том, что выбирает тип 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
}

Ответ 6

Попробуйте следующий код

var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as CustomTableViewCell

https://github.com/iappvk/TableView-Swift

Ответ 7

Если вы не используете Storyboard, тогда создайте новый файл в качестве подкласса UITableViewCell, установите флажок "также создавать xib файлы" после этого установите свою собственную ячейку. и вот код для tableview

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!


}

Ответ 8

Попробуйте следующий код:

var cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellTableView") as? CustomCellTableView

Ответ 9

Расширение NSOject

extension NSObject {    
    var name: String {
        return String(describing: type(of: self))
    } 
    class var name: String {
        return String(describing: self)
    }
}

Свойства на пользовательском TableViewCell

class var nib: UINib {
    return UINib(nibName:YourTableViewCell.name, bundle: nil)
}
class var idetifier: String {
    return YourTableViewCell.name
}

Добавить в UIViewController

self.tableView.registerNib(YourTableViewCell.nib, forCellReuseIdentifier: YourTableViewCell.idetifier)

let cell = tableView.dequeueReusableCellWithIdentifier(YourTableViewCell.idetifier, forIndexPath: indexPath) as! YourTableViewCell

Ответ 10

Это чисто быстрое обозначение работает для меня

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
var cellIdentifier:String = "CustomFields" 
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
 if (cell == nil) 
{ 
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil) cell = nib[0] as? CustomCell
 } 
return cell! 
}