繁体   English   中英

在Swift中创建静态单元格

[英]Creating static cells in Swift

我正在尝试在UITableViewCell创建静态单元格。 我首先在Interface Builder中添加了2个单元格,并为它们指定了标识符titlenews 然后我创建了一个包含这两个标识符的数组,并将其添加到cellForRowAtIndexPath 但是我一直收到以下错误:

'unable to dequeue a cell with identifier title - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

阵列

var menuItems = ["title", "news"]

tableView委托方法

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 2
}

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

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

    let cell = tableView.dequeueReusableCellWithIdentifier(menuItems[indexPath.row], forIndexPath: indexPath) as! UITableViewCell

    cell.backgroundColor = UIColor(white: 0.2, alpha: 1.0)

    var bottomView: UIView = UIView(frame: CGRectMake(0, cell.frame.height-1, cell.frame.width, 1))
    bottomView.backgroundColor = UIColor(white: 0.2, alpha: 0.15)
    cell.contentView.addSubview(bottomView)

    return cell
}

看起来您必须手动为单元注册UITableViewCell类。 你可以通过电话来实现这一点

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: menuItems[indexPath.row])

在你的viewDidLoad()函数中的UITableViewDataSourcecellForRowAtIndexPath函数

与错误消息描述的一样,如果您将它们创建为空UI文件,则必须注册它们。 这可以简单地放在viewDidLoad函数中。

override func viewDidLoad() {
        super.viewDidLoad()

        var nib = UINib(nibName: "OrangeCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "oranges")

        var nib2 = UINib(nibName: "AppleCell", bundle: nil)
        tableView.registerNib(nib2, forCellReuseIdentifier: "apples")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM