【问题标题】:Apply an IBAction only to a single cell仅将 IBAction 应用于单个单元格
【发布时间】:2015-08-27 10:40:24
【问题描述】:

我有一个带有原型单元格的 tableView;用这个func 设置单元格高度

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return cellHeight
    }

有了这个action,我改变了 UIButton 内部的单元格高度

@IBAction func changeCellHeight(sender: UIButton)
    {
        if cellHeight == 44
        {
            cellHeight = 88
        } else {
            cellHeight = 44
        }
        tableView.beginUpdates()
        tableView.endUpdates()
    }

现在我只需要更改选定单元格的高度(不是每个单元格);所以我定义 var index: NSIndexPath! 我实现了这个func

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        index = self.tableView.indexPathForSelectedRow()!
        println("Cella " + "\(index)")
    }

正如我在控制台中预期的那样,Xcode 会打印选定的单元格 (<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0})。

所以我的麻烦是如何在IBAction 中使用var index

提前致谢。

【问题讨论】:

    标签: swift ibaction didselectrowatindexpath nsindexpath


    【解决方案1】:

    要根据选择更改高度,如果您已经实现 didSelectRowAtIndexPath 方法,则不需要 IBAction。

    首先对您的didSelectRowAtIndexPath 方法稍作改动-

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 
       // You don't need to do this -> index=self.tableView.indexPathForSelectedRow()!
       index = indexPath;
       println("Cella " + "\(index)")
    
       tableView.beginUpdates()
       tableView.endUpdates()
    }
    

    然后对您的heightForRowAtIndexPath 方法稍作改动-

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
        {
           if index == indexPath {
                return 88
            }
           else{
               return 44
           }
        }
    

    【讨论】:

    • 非常感谢您的回答!但我认为我必须使用 UIButton:请参阅以下链接 stackoverflow.com/q/32238174/5143178
    • 但是你能解释一下 index = self.tableView.indexPathForSelectedRow() 之间有什么区别吗?并且 index = indexPath?
    • 如果您在 TableView 的委托方法 didSelectRowAtIndexPath 中,那么该方法已经为您提供了索引路径。请参阅方法签名。因此,您不必调用 indexPathForSelectedRow() 方法。但是,如果您在该类中的其他任何位置(例如在 Action 方法中),那么您不知道 indexPath 是什么。因此,在这种情况下,您可以调用 indexPathForSelectedRow() 方法来获取选定的 indexPath。你可以在你的 didSelectRowAtIndexPath 方法中做同样的事情,但这只会导致实现 didSelectRowAtIndexPath 方法的目的失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2017-11-23
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多