[英]Custom UITableViewCell in Swift programmatically
我希望以編程方式在Swift中創建一個UITableView和相應的自定義UITableViewCell。 表視圖工作得很好,但似乎單元格標簽沒有實例化 - 它們返回為零。
在調整元素大小時,我也不知道如何引用內容視圖大小。
的UITableViewCell
import UIKit
class BusUITableViewCell: UITableViewCell {
var routeNumber: UILabel!
var routeName: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
routeName = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) // not sure how to refer to the cell size here
contentView.addSubview(routeNumber)
contentView.addSubview(routeName)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
UITableView委托和源代碼
import Foundation
import UIKit
class BusUITableView: NSObject, UITableViewDelegate, UITableViewDataSource {
var routeService: RouteService = RouteService()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var busRoutes: [Route] = routeService.retrieve()
return busRoutes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:BusUITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as BusUITableViewCell
var busRoutes: [Route] = routeService.retrieve()
cell.routeName.text = "test" // test string doesn't work, returns nil
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
查看控制器
mainTableView.registerClass(BusUITableViewCell.self, forCellReuseIdentifier: "cell")
如果您沒有鏈接到故事板中的原型單元格,那么您需要使用registerClass(_ cellClass: AnyClass, forCellReuseIdentifier identifier: String)
針對您的tableView registerClass(_ cellClass: AnyClass, forCellReuseIdentifier identifier: String)
您的單元格的類
在你的情況下,你會使用這樣的東西
tableview.register(BusUITableViewCell.self, forCellReuseIdentifier:"cell")
此外,如果沒有NIB文件,則不會調用awakeFromNib
。
編輯:.registerClass()已重命名為.register()
考慮到你“以編程方式”(沒有nib文件)這樣做,你就是awakeFromNib()永遠不會調用。 您可以創建一個nib,並將其鏈接到此支持文件,並仍然以編程方式創建和使用該單元。 或者......選擇一個不同的位置(如初始化程序)來創建子視圖並將其添加到單元格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.