[英]CustomCell in UITableView Swift 2
我已经创建了一个UITableView,并且想要动态创建单元格来保存诸如名称,持续时间和价格之类的信息。
我有以下代码:
class MyCustomTableViewCell: UITableViewCell {
@IBOutlet weak var price: UILabel!
}
class TableViewController: UITableViewController {
var data = [["name1","amount1","duration1"],["Name2","amount2","duration2"],["name3","amount3","duration3"]]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomTableViewCell", forIndexPath: indexPath) as! MyCustomTableViewCell
cell.textLabel?.text = "\(data[indexPath.row][0])"
cell.detailTextLabel?.text = "\(data[indexPath.row][1])"
cell.price.text = "\(data[indexPath.row][2])"
return cell
}
}
我在情节提要板上出现以下错误:
从TableViewController到UILabel的价格出口无效。 插座不能连接到重复的内容。
我了解错误的含义,但是我认为MyCustomTableViewCell类意味着price变量是动态的,因此不尝试重复静态内容。
任何帮助,将不胜感激 :)
我从Askash那里得到了这个答案,但是我的代码似乎有些混乱,所以我以为id会发布我的答案,以防其他人对此有麻烦。
步骤1.确保使用以下代码创建TableViewController并确保在情节提要板上设置了它:
class TableViewController: UITableViewController {
var data = [["name1","amount1","duration1"],["Name2","amount2","duration2"],["name3","amount3","duration3"]]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
cell.textLabel?.text = "\(data[indexPath.row][0])"
cell.detailTextLabel?.text = "\(data[indexPath.row][2])"
cell.price.text = "£\(data[indexPath.row][2])"
return cell
}
}
在故事板上,单击TableViewController,单击“显示身份检查器”,然后在类部分中粘贴“ TableViewController”:
步骤2创建一个新的TableViewCell类。 -转到“文件”>“新建”>“文件...”>“ IOS源”>“可可触摸类”>“下一步”,并创建一个包含UITableViewCell子类的TableViewCell类:
步骤3将TableViewCell分配给原型单元并设置恢复ID。
单击情节提要中的原型单元,单击显示“属性检查器”,然后将“ TableViewCell”粘贴到类部分以及标识符类型“单元”中:
步骤4在“ TableViewCell”类中创建标签“ Price”的出口。 (使用Ctrl +拖动)并将其命名为“价格”。
TableViewCell中的代码应如下所示:
TableViewCell类:UITableViewCell {
@IBOutlet weak var price: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.