2016-02-19 85 views
4

我可以告诉如何从here的objective-c中执行此操作,但是如何将其转换为swift?UITableView:如何单击按钮时动态更改单元格高度? Swift

我有一个UITableView自定义TableViewCells有一个名为“expandButton”的UIButton。我试图找出如何在点击该单元格的expandButton时更改该特定单元格的高度。

此外,当它再次被点击时,它应该变回原来的大小。 我对ObjectiveC不熟悉,所以请在Swift中帮助我。预先感谢一堆!

这是我到目前为止有:

//Declaration of variables as suggested 
     var shouldCellBeExpanded:Bool = false 
     var indexOfExpendedCell:NSInteger = -1 

现在视图控制器内。注意:TableViewCell是我的自定义单元格的名称。

//Inside the ViewController 
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    if let cell:TableViewCell = TableViewCell() { 

     cell.stopWatch = stopWatchBlocks[indexPath.row] 

     cell.expandButton.tag = indexPath.row 

     //Adding action to the expand button 
     cell.expandButton.addTarget(self, action: "expandButtonAction1:", forControlEvents: UIControlEvents.TouchUpInside) 

     return cell 

    } 

} 

现在,按钮操作方法:

func expandButtonAction1(button:UIButton) { 

    button.selected = !button.selected 

    if button.selected { 

     indexOfExpendedCell = button.tag 
     shouldCellBeExpanded = true 

     self.TableView.beginUpdates() 
     self.TableView.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfExpendedCell, inSection: 0)], withRowAnimation: .Automatic) 
     self.TableView.endUpdates() 

     button.setTitle("x", forState: UIControlState.Selected) 
    } 

    else if !button.selected { 

     indexOfExpendedCell = button.tag 
     shouldCellBeExpanded = false 

     self.TableView.beginUpdates() 
     self.TableView.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfExpendedCell, inSection: 0)], withRowAnimation: .Automatic) 
     self.TableView.endUpdates() 

     button.setTitle("+", forState: UIControlState.Normal) 
    } 
} 

终于HeightForRowAtIndexPath

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

    if shouldCellBeExpanded && indexPath.row == indexOfExpendedCell { 
     return 166.0 
    } 
    else { return 91.0 } 
} 

我想我失去了一些东西,因为单元并非点击一次在扩大,但它确实不会'缩水'回到91!

我在这里做错了什么?

回答

7

尽量不要使用选定的标签作为切换单元状态,如此。一旦选中一个单元格,再次点击它将不会取消选择。相反,你可以只使用shouldCellBeExpanded标志:

func expandButtonAction1(button:UIButton) { 

    shouldCellBeExpanded = !shouldCellBeExpanded 
    indexOfExpendedCell = button.tag 

    if shouldCellBeExpanded { 
     self.TableView.beginUpdates() 
     self.TableView.endUpdates() 

     button.setTitle("x", forState: UIControlState.Normal) 
    } 

    else { 
     self.TableView.beginUpdates() 
     self.TableView.endUpdates() 

     button.setTitle("+", forState: UIControlState.Normal) 
    } 
} 

而且,从我的经验reloadRowsAtIndexPath方法是不必要的。除非您需要自定义动画,否则单独使用beginUpdates()和endUpdates()应该会有效。

+0

太棒了!感谢您的提示和答案。这很好! –

相关问题