Dav*_*ard 51 interface-builder uitableview ios swift
考虑以下简单视图控制器:
class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var items = ["One", "Two", "Three"]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
        self.tableView.dataSource = self
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
        cell.titleLabel!.text = self.items[indexPath.row]
        return cell
    }
}
和自定义单元格视图:
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!   
}
此代码导致以下错误.
致命错误:在展开Optional值时意外发现nil
titleLabel是零 - 不清楚为什么.设置UITableViewCell(像textLabel)的默认属性工作得很好.
我正在使用笔尖来定制单元格.
标签和表格视图都正确连接到它们的IBOutlets.
 

原型单元格和自定义笔尖视图都标记为具有CustomTableViewCell类.
我是iOS开发的新手,我错过了一些明显的东西吗?
kel*_*ket 51
首先,您正在使用nib文件将自定义单元格加载到表格中.如果你是Swift/Cocoa的新手,那可能会比它更值得头疼.我暂时将所有内容都移到故事板上.而不是使用nib文件单击,转到Storyboard,单击您的UITableView并确保TableView的内容设置为Dyanamic Prototypes:

接下来,单击原型单元格(表视图中唯一的单元格)并将类CustomTableViewCell设置为并将其重用标识符设置为customCell:
 

接下来,将标签添加到原型单元格并将其链接到CustomTableViewCell类中的IBOutlet .customCell只要您在故事板中设置重用标识符,就不需要注册.删除此行:
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
它应该运行.
LDN*_*NZh 42
试试这个
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    var items = ["One", "Two", "Three"]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")// CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
        self.tableView.dataSource = self
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as CustomTableViewCell
        cell.titleLabel!.text = self.items[indexPath.row]
        return cell
    }
}
小智 11
像这样注册你的笔尖:
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "PickerCell", bundle: bundle)
collectionViewPicker.register(nib, forCellWithReuseIdentifier: "cell")
你应该dequeueReusableCellWithIdentifier:forIndexPath用来使细胞出列.
如果您使用故事板来创建单元格,则不需要注册该类以供重用,因为如果您设置了reuseIdentifier,则storyboard会为您执行此操作.
| 归档时间: | 
 | 
| 查看次数: | 36002 次 | 
| 最近记录: |