UITableViewCell

时间:2016-06-08 15:23:58

标签: swift uitableview switch-statement

我有一个TableView和一个基于数组的Cell。现在我想基于数组中显示的数组输入更改变量。

var array = ["first", "second", "third"]
var result = String

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let Cell = self.tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath) as UITableViewCell

        Cell.textLabel?.text = array[indexPath.row]

// and here I need the content of the Cell

        switch Cell."content argument" {
            case "first":
                var result = "works"
            case "second":
                var result = "works also"
            case "third":
                var result = "what a surprise, works also"
            default:
                var result = "doesn't work"
        }  

        return Cell

    }

在这里我需要参数来获取Cell的内容。并且,请不要和#34;你必须创建一个新的文件或功能或扩展",不,请只是参数!

1 个答案:

答案 0 :(得分:0)

根据Cell.textLabel?.text切换时遇到的问题是textLabel为Optional,因此它的文字也是OptionalOptional是一个包含两个案例{1}和.Some的枚举,这就是为什么您的案例无效。

有两种可能的解决方案。

  1. 将您的开关置于.None声明中:

    if let
  2. 不要根据手机的内容进行切换,而是根据您的非可选数据进行切换:

    Cell.textLabel?.text = array[indexPath.row]
    
    if let text = Cell.textLabel?.text {
        switch text {
            case "first":
                var result = "works"
            case "second":
                var result = "works also"
            case "third":
                var result = "what a surprise, works also"
            default:
                var result = "doesn't work"
        }
    }
    
  3. 然后出现了问题,即您正在制作大量未使用的局部变量,这些变量恰好都被命名为结果。所以,让我们更好地将它设置为常量并将其设置在开关中,并将结果添加到单元格中,如下所示:

    let text = array[indexPath.row]
    Cell.textLabel?.text = text
    
    switch text {
        case "first":
            var result = "works"
        case "second":
            var result = "works also"
        case "third":
            var result = "what a surprise, works also"
        default:
            var result = "doesn't work"
    }
    

    这里需要的所有代码:

        let text = array[indexPath.row]
    
        let result: String
        switch text {
            case "first":  result = "works"
            case "second": result = "works also"
            case "third":  result = "what a surprise, works also"
            default:       result = "doesn't work"
        }
    
        Cell.textLabel?.text = text
        Cell.detailTextLabel?.text = result