簡體   English   中英

單擊按鈕展開 tableview 單元格

[英]Expand tableview cell on button click

我用約束做了一些簡單的技巧。 我制作了可擴展的tableView cell cell單擊它會打開新單元格(黑色)(下圖是為了更容易理解)。

我的問題是如何使它與頂部單元格內看起來像"V"的按鈕一起工作。 如果單擊cell我希望它至少旋轉 90°。 我怎么能做到。

這就是我讓它擴展的方式:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if(selectedIndex == indexPath.row){
            return 210
        }else{
            return 135
        }
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if (selectedIndex == indexPath.row){
            selectedIndex = -1
        }else{
            selectedIndex = indexPath.row
        }

        self.productstable.beginUpdates()
        self.productstable.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.productstable.endUpdates()
    }

您可以使用閉包實現:

typealias arrowButtonTappedBlock = (button:UIButton) -> Void

在您的自定義單元格中聲明一個closure ,如下所示:

var arrowButtonTapped : arrowButtonTappedBlock!

並在箭頭按鈕上單擊操作調用閉包,如下所示:

if arrowButtonTapped != nil {
            arrowButtonTapped(button: sender as! UIButton)
        }

cellForRowAtIndexPath :設置閉包並執行您在didSelectRowAtIndexPath:執行的操作didSelectRowAtIndexPath:

cell!.arrowButtonTapped = { (button:UIButton) -> Void in

                if (self.selectedIndex == indexPath.row){
                    self.selectedIndex = -1
                }else{
                    self.selectedIndex  = indexPath.row
                }

                self.tableview.beginUpdates()
                self.tableview.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
                self.tableview.endUpdates()
} 

你可以用簡單的方法做到這一點

  1. Delare var selectedRowIndex = -1

  2. 為您的自定義單元創建協議

    protocol TableViewCellDelegate { func BtnExpendTapped(_ cell: CustomCell) }
  3. 在您的自定義單元聲明協議中並為按鈕添加操作方法

    var delegate: TableViewCellDelegate?

     @IBAction func actionExpendBtnTap(_ sender: UIButton){ delegate?.BtnExpendTapped(self) }
  4. 在您的 Height for Row 方法中,根據您的要求添加您的 Expended 和 normal 高度

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == selectedRowIndex { return 270 //Expanded } return 138.5 //Not expanded }
  5. 在視圖控制器中使用您的協議委托並添加委托方法

func BtnExpendTapped(_ cell: CustomCell) {
     if let indexPath = tblView.indexPath(for: cell) {
         if selectedRowIndex == indexPath.row {
             selectedRowIndex = -1
         } else {
             selectedRowIndex = indexPath.row
         }
        tblView.reloadRows(at: [indexPath], with: .none)
     }
 }


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM