如何在tableView中为单元格指定文本?

时间:2014-10-14 09:33:48

标签: ios swift uitableview

我正在swift中创建一个taskList应用程序,我的代码是:

    import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    var tableView : UITableView!
    var textField : UITextField!
    var tableViewData = ["My Text 1", "My Text 2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        //Set up textField

        self.textField = UITextField(frame: CGRectMake(0, 0, self.view.bounds.size.width, 100))
        self.textField.backgroundColor = UIColor.redColor()
        self.view.addSubview(self.textField)

        //Set up table view

        self.tableView = UITableView(frame: CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height-100), style: UITableViewStyle.Plain)
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.view.addSubview(self.tableView)


    }
    //TableView Data source Delegate

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

        return tableViewData.count
    }

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

        let myNewCell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        //Here is the error
        myNewCell.text = self.tableViewData[indexPath.row]

        return myNewCell
    }
}

错误是:

'text' is unavailable:APIs deprecated as of iOS 7 and earlier are unavailable in Swift

我是从教程中做到的,那个人使用的是xCode 6.0,我有xCode 6.1 beta版本我认为这是问题,因为我使用的是测试版。 任何人都可以解释一下这个错误是什么,我是swift的新手,所以任何人都可以告诉我该怎么做?

3 个答案:

答案 0 :(得分:2)

您需要使用

myNewCell.textLabel?.text = self.tableViewData[indexPath.row]
过去曾经是:

myNewCell.text = self.tableViewData[indexPath.row]

但是他们将text属性嵌入到textLabel属性中。

答案 1 :(得分:1)

使用此

myNewCell.textLabel?.text = self.tableViewData[indexPath.row]

答案 2 :(得分:1)

您需要调用textLabel并且textLabel是可选的,因此您需要打开它:

if let textLabel = myNewCell.textLabel {
    textLabel.text = self.tableViewData[indexPath.row]
}

myNewCell.textLabel?.text = self.tableViewData[indexPath.row]
相关问题