Jho*_*nny 7 uitableview ios swift
我收到一条错误消息" 从Swift nil解包时意外发现Optional",下面是类.该行发生错误:
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
Run Code Online (Sandbox Code Playgroud)
我有一个自定义单元类,其中2个UILabels标记为1和2,插座已设置
import UIKit
import Foundation
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var objects = NSMutableArray()
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]]
@IBOutlet
var tableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;//self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
//cell.textLabel?.text = self.items[indexPath.row]
//return cell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
(cell.contentView.viewWithTag(2) as UILabel).text = object["lastName"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*Rob 23
如果你想使用自定义单元格布局,我建议
子类UITableViewCell:
// CustomTableViewCell.swift
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
}
Run Code Online (Sandbox Code Playgroud)在故事板中创建表视图.将单元格原型添加到storyboard中的tableview.设计细胞原型(添加你想要的任何标签).
将单元格原型的故事板标识符指定为您想要的任何内容(MyCell在您的示例中).

在此示例中,指定单元原型的基类CustomTableViewCell:

IBOutlet连接单元原型和UITableViewCell子类之间的引用.

请注意IBOutlet引用左侧的实心项目符号.这表明插座正确连接.
cellForRowAtIndexPath在您的数据源中实现,例如在Swift 3中:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! CustomTableViewCell
let person = dataArray[indexPath.row]
cell.firstNameLabel.text = person["firstName"]
cell.lastNameLabel.text = person["lastName"]
return cell
}
Run Code Online (Sandbox Code Playgroud)
或者在Swift 2中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! CustomTableViewCell
let person = dataArray[indexPath.row]
cell.firstNameLabel.text = person["firstName"]
cell.lastNameLabel.text = person["lastName"]
return cell
}
Run Code Online (Sandbox Code Playgroud)请注意,如果使用电池的原型,你就不会想打电话给registerClass在viewDidLoad.故事板将自动为您重新注册您的自定义类(因为您在步骤3和4中已完成的操作).
编辑2:这个解决方案可能更适合您的目的.通过这个,您可以为自己的UITableViewCell创建自己的类,并将其用于重用模式.评论在代码中:
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
// The data
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]]
// The outlet to your tableview in the ViewController in storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Create a nib for reusing
let nib = UINib(nibName: "MyCell", bundle: nil)
// Register the nib for reusing within the tableview with your reuseidentifier
tableView.registerNib(nib, forCellReuseIdentifier: "MyCell")
// Set delegate and datasource to self (you can do that in interface builder as well
tableView.delegate = self
tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count; // return the number of datasets
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create a reusable cell with the reuse identifier you registered in viewDidLoad and cast it to MyCell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell
let object = dataArray[indexPath.row] as NSDictionary
// set the strings matching your array
cell.label1.text = object["firstName"] as? String
cell.label2.text = object["lastName"] as? String
// return the cell
return cell
}
// some example for the delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
// class for you own UITableViewCell
// has own xib file
class MyCell: UITableViewCell {
// two outlets representing two labels in the xib file
@IBOutlet private weak var label1: UILabel!
@IBOutlet private weak var label2: UILabel!
}
Run Code Online (Sandbox Code Playgroud)
为此,您必须使用正确的名称创建一个xib文件(在本例中为MyCell).它应该类似于:

设置自定义视图和插座的类非常重要.
-------------------------------------其他解决方案----------- ---------------------------
编辑:我认为你没有初始化你自己的类'MyCell',而是使用reuseIdentifier'MyCell'来初始化Apple的'UITableViewCell'类.这就是使用UITableViewCell的解决方案:
该行(cell.contentView.viewWithTag(1) as UILabel)不仅是对特定类的强制转换,它还展开了Optional(UIView).你在其他情况下用'!'来做到这一点.所以问题是:你正在创建一个UITableViewCell实例,这是Apple创建的一个类.您希望使用特定标记获取该视图内的子视图.你怎么知道苹果给了他们这些标签?你真正想要的是创建一个具有特殊样式的UITableViewCell实例,并设置textLabels的值,如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Create an instance of UITableViewCell. Style is .Subtitle but could be others as well
var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as? UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
// set the strings matching your array
cell?.textLabel?.text = object["firstName"] as? String
cell?.detailTextLabel?.text = object["lastName"] as? String
// return the cell
return cell!
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16410 次 |
| 最近记录: |