Swift - 检索存储在自定义tableview-cells中的信息

时间:2015-01-07 16:41:37

标签: uitableview swift uigesturerecognizer custom-cell didselectrowatindexpath

我在自定义单元格中实现了longPressGesture,现在我需要检索存储在这些单元格中的信息。

我的cellForRowAtIndexPath函数如下所示:

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

    let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "cellLongPressed:")
    longPress.delegate = self
    longPress.minimumPressDuration = 1
    longPress.numberOfTouchesRequired = 1

    let cellID = "cell"
    var mcell:CusCell = self.tv.dequeueReusableCellWithIdentifier("cell") as CusCell

    mcell.addGestureRecognizer(longPress)

    let data = mainList[indexPath.row] as SecondModel

    var dateStr:String = String()
        dateStr = printDate(data.date)

        mcell.mainLabel.text = data.receiver
        mcell.recLabel.text = "Message sent at \(dateStr)"
        mcell.imageLabel.image = UIImage(named: icons[0])
        mcell.messType = messageType

返回mcell     }

我的didSelectRowAtIndexPath函数如下所示:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let selectedCell: CusCell = tv.cellForRowAtIndexPath(indexPath) as CusCell

    messagType = selectedCell.messType

    println(messagType)

}

我的cellLongPressed-function看起来像这样:

func cellLongPressed(gestureRecognizer:UIGestureRecognizer) {

    if (gestureRecognizer.state == UIGestureRecognizerState.Ended) {
        println("STATE ENDED")
        //Do Whatever You want on End of Gesture
    }
    else if (gestureRecognizer.state == UIGestureRecognizerState.Began){
        println("STATE BEGAN")
        //Do Whatever You want on Began of Gesture
    }
}

现在你可能猜到,整数存储在" selectedCell.messType"从来没有打印过。我真的不明白为什么这不起作用,是我对“选择的细胞”的宣言。错?

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:4)

如果messageType是模型的一部分,为什么不能从模型中读取数据?从单元格读回数据不是一个好方法。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)  {

    let data = mainList[indexPath.row] as SecondModel
    var messagType = data.messageType
    println(messagType)

}

如果要在长按事件

中记录值
func cellLongPressed(gestureRecognizer:UIGestureRecognizer) {

    if (gestureRecognizer.state == UIGestureRecognizerState.Ended) {
        var point = gestureRecognizer.locationInView(self.tableView)
        if let indexPath = self.tableView.indexPathForRowAtPoint(point)
        {
            let data = mainList[indexPath.row] as SecondModel
            var messagType = data.messageType
            println(messagType)
        }
    }
    else if (gestureRecognizer.state == UIGestureRecognizerState.Began){

    }
}