簡體   English   中英

將消息從View Controller傳遞到Swift中的類

[英]Passing message from View Controller to a class in Swift

通過使用委托,我試圖將數據從視圖控制器傳遞到TableView類,該類將顯示正確數量的單元格。 首先,我需要將數組傳遞給該類(此處使用String代替進行調試)

在我的ViewController中:

protocol GroupBillVCDelegate{
  func passFriendArray(string: String)
}

...
class GroupBillViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
    var delegate:GroupBillVCDelegate? // for delegate passing message

    ...

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (tableView == self.FriendTableView){
            let friendListCell = tableView.dequeueReusableCell(withIdentifier: "friendListCell") as! CategoryRow

            // transfer friends array to CategoryRow
            self.delegate?.passFriendArray(string: "Hello There")

            return friendListCell
        }
    }
}

在TableViewCell類中:

class CategoryRow: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, GroupBillVCDelegate {

    var s:String = String()

    func passFriendArray(string: String) {
        s = string
        print(string)
    }

...

    // used for horizontal scrolling
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        passFriendArray(string: s)   // message supposed to appear here
        print ("TEST")
        return 10
    }

...

}

我在設置代表時遇到麻煩。 當我運行時,控制台不會顯示該消息。 為什么不通過?

可以將代表視為辦公桌上的對講機,該對講機可以連接到助手室。

這行:

var delegate:GroupBillVCDelegate? // for delegate passing message

定義對講機,但不連接任何東西。 如果您按下對講機上的按鈕,則它不會連接任何東西。

代碼self.delegate?.passFriendArray(string: "Hello There")

如果有委托,則使用“可選鏈接”將消息發送給委托,如果沒有委托,則使用丟棄消息。

您缺少的是為委托分配一些東西:

self.delegate = someObjectThatConformsToGroupBillVCDelegateProtocol

委托是一對一的關系。

話雖這么說,讓表視圖單元格成為視圖控制器的委托真的沒有任何意義。 表格視圖有多個單元格。 視圖控制器的委托應該是哪個單元格? 為什么那個細胞而不是另一個?

暫無
暫無

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

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