【发布时间】:2015-08-09 03:36:35
【问题描述】:
我正在尝试从另一个类内部更改 UITableView(一个类的属性)中的 UILabel 的文本,但我遇到了麻烦。代码是这样的(问题在最后,在myDataSource的didSelectRowAtIndexPath方法中)
视图控制器
class ViewController: UIViewController
{
//MARK: Properties
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var myLabel: UILabel!
//needed so data from myDataSource is retained by ViewController and not just thrown away
let importedDataSource = myDataSource()
override func viewDidLoad()
{
super.viewDidLoad()
myTableView.dataSource = myDataSource()
myTableView.delegate = myDataSource()
}
override func didReceiveMemoryWarning()
{super.didReceiveMemoryWarning()}
}
UITableViewDataSource 和委托
class myDataSource: NSObject, UITableViewDataSource, UITableViewDelegate
{
let cellIdentifier = "myTableViewCell"
let myArray = ["Label one", "Label two", "Label three"]
//MARK: TableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{return 1}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{return myArray.count}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! myTableViewCell
cell.myCellLabel.text = myArray[indexPath.row]
return cell
}
//MARK:TableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
//This Line Here returns the error
ViewController().myLabel.text = "test"
//I want the end product to be ViewController().myLabel.text = myArray[indexPath.row], but left it as "test" just to simplify and isolate the error
}
}
(还有一个名为 myTableViewCell 的 UITableViewCell 类,但我省略了它以使其更短)
在选择其中一行时,运行会返回“致命错误:在展开可选值时意外发现 nil”。我应该如何调用 myLabel 以避免这个问题?我已经尝试通过 ctrl 将它从情节提要中拖动,将它作为 myDataSource 中的 @IBOutlet 连接起来,但正如我所料,它只允许我将它连接到视图控制器。
抱歉,代码与两个名称相似的标签有点混淆。我正在尝试调用在 ViewController 中创建的 myLabel var(第一段代码),而不是在 myTableViewCell 中创建的 myCellLabel(未显示)
【问题讨论】:
标签: ios uitableview class uilabel swift2