【问题标题】:How to pass data from UI Table View to UI Collection View inside Table View Cell?如何将数据从 UI Table View 传递到 Table View Cell 内的 UI Collection View?
【发布时间】:2019-07-26 11:47:52
【问题描述】:

我使用 xib 在我的表格视图单元格上有 ui 集合视图。 我想将从 API 获得的数据传递到表格视图单元格内的 ui 集合视图

这是我的代码

型号

class MessageTextType {

var messageType: String = ""
var messageFromMe: String = ""
var date: String = ""
var type: String = ""
var text: String = ""
var image: String = ""
var imagePreview: String = ""
var time: String = ""
var speech: String = ""
var resolvequery: String = ""
var columnCarousel: String = ""


}

表格视图

 var messageTextArray : [MessageTextType]  = [MessageTextType]()
    var messageFromMe : [MessageInput] = [MessageInput]()


override func viewDidLoad() {
    super.viewDidLoad()

    chatTableView.delegate = self
    chatTableView.dataSource = self


    chatMessage.delegate = self

    chatTableView.register(UINib(nibName: "MessageText", bundle: nil), forCellReuseIdentifier: "MessageText")

    chatTableView.register(UINib(nibName: "MessageFromMe", bundle: nil), forCellReuseIdentifier: "MessageFromMe")

    chatTableView.register(UINib(nibName: "ChatImage", bundle: nil), forCellReuseIdentifier: "MessageImage")

    chatTableView.register(UINib(nibName: "MessageCarousel", bundle: nil), forCellReuseIdentifier: "MessageCarousel")


    configureTableView()

    chatTableView.separatorStyle = .none

    showNavItem()


}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let chatinfo = messageTextArray[indexPath.item]


    if chatinfo.messageType == "chatInput" {
        let cell : MessageFromMe! = tableView.dequeueReusableCell( withIdentifier: "MessageFromMe") as? MessageFromMe


        cell.chatMe.text = chatinfo.messageFromMe
        cell.time.text = chatinfo.time

                    return cell

    }
    else{

        if chatinfo.type == "image" {

            let cell : ChatImage! = tableView.dequeueReusableCell( withIdentifier: "MessageImage") as? ChatImage


            let remoteImageURL = URL(string: chatinfo.image)!

                     Alamofire.request(remoteImageURL).responseData { (response) in
                            if response.error == nil {
                                     print(response.result)

                                     if let data = response.data {
                                            cell.chatImage.image = UIImage(data: data)

                                         }
                                }
                        }

            return cell


        }else if chatinfo.type == "text" {

            let cell : MessageText! = tableView.dequeueReusableCell( withIdentifier: "MessageText") as? MessageText

            cell.chatText.text = chatinfo.text

            return cell

        }

        else {

            let cell : MessageCarousel! = tableView.dequeueReusableCell( withIdentifier: "MessageCarousel") as? MessageCarousel

            return cell


        }


    }

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return messageTextArray.count

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableView.automaticDimension

}

func configureTableView() {
    chatTableView.rowHeight = UITableView.automaticDimension
    chatTableView.estimatedRowHeight = 500.0

}



@IBAction func sendPressed(_ sender: Any) {
    chatInput()

    getDataText()
    chatMessage.text = ""
}

func chatInput() {
    let messageRespon = MessageTextType()

    let date = Date()
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    formatter.dateStyle = .none


    messageRespon.messageType = "chatInput"
    messageRespon.messageFromMe = chatMessage.text!
    messageRespon.time = formatter.string(from: date)
    messageTextArray.append(messageRespon)

    configureTableView()
    chatTableView.reloadData()


}


func getDataText() {

    startAnimating(type: NVActivityIndicatorType.ballPulseSync)
    let id = UserDefaults.standard.object(forKey: "id") as! String

    let chatParams : [String : Any] = [            "user_id": id,
        "bot_id": "dBmK5m",
        "query": chatMessage.text!
    ]

    let token = UserDefaults.standard.object(forKey: "token") as! String

    let headersku: HTTPHeaders = [
        "Content-Type":"application/json",
        "Accept": "application/json",
        "Authorization": "Bearer \(token)"
    ]

    Alamofire.request(base_url+"/chat", method: .post, parameters: chatParams,encoding: JSONEncoding.default, headers: headersku)
        .responseJSON {
            response in
            if response.result.isSuccess {

                let loginJSON : JSON = JSON(response.result.value!)
                print(loginJSON)

                let output = loginJSON["result"]["output"]

                for (_, subJson):(String, JSON) in output {
                    let text = subJson["text"].stringValue
                    let type  = subJson["type"].stringValue
                    let speech = subJson["speech"].stringValue
                    let image = subJson["originalContentUrl"].stringValue
                    let date = loginJSON["timestamp"]["date"].stringValue
                    let resolvequery = loginJSON["resolvequery"].stringValue
                    let columns = subJson["columns"]

                    let message = MessageTextType()



                    message.text = text
                    message.messageType = "text"
                    message.type = type
                    message.speech = speech
                    message.image = image
                    message.date = date
                    message.resolvequery = resolvequery

                    self.messageTextArray.append(message)


                    if type == "text" {

                        let utterance = AVSpeechUtterance(string: output[0]["text"].stringValue +
                            ".   "+output[1]["text"].stringValue)

                        utterance.rate = 0.5
                        utterance.voice = AVSpeechSynthesisVoice(language: "id-ID")


                        let voice = AVSpeechSynthesizer()
                        voice.speak(utterance)


                    }



                }



                self.configureTableView()
                self.chatTableView.reloadData()

                self.stopAnimating()

                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1, execute: {
                    let indexPath = IndexPath(row: self.messageTextArray.count-1, section: 0)
                    self.chatTableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: true)
                })

            }

            else {

                let alertController = UIAlertController(title: "warning", message: "server sedang bermasalah , coba lagi", preferredStyle: .alert)

                let action1 = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction) in

                    self.stopAnimating()

                }


                alertController.addAction(action1)
                self.present(alertController, animated: true, completion: nil)
            }
    }

}

表格视图单元格内的集合视图

import UIKit
class MessageCarousel: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var carouselImage: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    self.carouselImage.dataSource = self
    self.carouselImage.delegate = self
    self.carouselImage.register(UINib.init(nibName: "CarouselViewCell", bundle: nil), forCellWithReuseIdentifier: "carouselViewID")
    self.carouselImage.reloadData()
}


override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "carouselViewID", for: indexPath as IndexPath) as! CarouselViewCell
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    print(indexPath.row)

}


}

【问题讨论】:

    标签: ios uitableview uicollectionview swift4


    【解决方案1】:

    你必须在cellrowAt方法中传递数据。

    更新您的代码:

    let cell : MessageCarousel! = tableView.dequeueReusableCell( withIdentifier: "MessageCarousel") as? MessageCarousel
     ** cell.yourDataArray = chatinfo.arrayColumns **
     cell.carouselImage.reloadData()
    return cel
    // yourInputArray is array that contain collectionview data
    
    
    
    class MessageCarousel: UITableViewCell {
     var yourDataArray = NSMutableArray() // or any other array.
     //.... your code
    }
    

    您必须更新您的模型MessageTextType,在MessageTextType 中添加columns 变量数组

    class MessageTextType {
          var arrayColumns : [Column]!
          //... your rest code
    }
    
    class Column {
    var thumbnailImageUrl : String!
    var title : String!
    
    public class func modelsFromDictionaryArray(array:NSArray) -> [Column]
    {
        var models:[Column] = []
        for item in array
        {
            models.append(Column(dictionary: item as! NSDictionary)!)
        }
        return models
    }
    
    
    
    required public init?(dictionary: NSDictionary) {
    
        thumbnailImageUrl       = dictionary["thumbnailImageUrl"] as? String ?? ""
        title                   = dictionary["title"] as? String ?? ""
    }
    
    init() {
    
    }
    }
    

    在 API 响应中添加此代码:

    let columns = Column.modelsFromDictionaryArray(array:subJson["columns"])
    message.arrayColumns = columns
    

    【讨论】:

    • 我的问题是我无法将模型传递给我的表格视图单元格内的 ui 集合视图。我想返回 collectionview 的 numberOfItemSection 作为我的模型计数。我在表格视图上的附加模型错了吗? ——
    • 你想把messageFromMe数组数据传给collectioview吗?
    • 您好,感谢 btw 将数据从表视图传递到 ui 集合视图。但是,实际上我想将我的列从 api 响应传递为 ui 集合视图上图像轮播的数据
    • 这是我的全部回复,我只想让我的列成为我的图像轮播的数据
    • 你必须创建包含列数据的数组而不是传递给collectionview。如果是私有的,顺便说一句你的项目链接
    【解决方案2】:
        import UIKit
    
        class ViewController : UIViewController {   
    
        }
    
        extension ViewController:UITableViewDataSource,UITableViewDelegate{
            // this is for your tableView
         In your tableView Cell :-
         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let chatinfo = messageTextArray[indexPath.item]   
                 let cell : MessageCarousel! = tableView.dequeueReusableCell( withIdentifier: "MessageCarousel") as? MessageCarousel
                if yourModelData != nil{
                 // reload collectionView
                }
    
                            return cell
            }
        }
    
        extension ViewController :UICollectionViewDataSource,UICollectionViewDelegate{
        // This is for Your CollectionView
            // In collection View
            func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
               if yourModelData.count != 0{
                   return yourModelData.count
            }
            return 0
            }
    
            func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "carouselViewID", for: indexPath as IndexPath) as! CarouselViewCell
             // handle Model here
                 let msg = yourModelData[indexPath.row]. messageFromMe
    
                return cell
            }
       }     
            // hope its worked for you
    

    【讨论】:

    • 我的问题是我无法将我的模型传递给我的表格视图单元格内的 ui 集合视图。我想返回 collectionview 的 numberOfItemSection 作为我的模型计数。我在表格视图上的附加模型错了吗?
    • 为 tableView 和 CollectionView 使用扩展
    • eg :- extension ViewController : UITableViewDataSource,UITableViewDelegate{ // 在此处添加您的数据源和委托 } 与集合视图相同
    • 你能举个例子吗?
    • 不要在 TableView Cell 类中实现你的 collectionView,使用扩展,我的意思是说在 Main ViewController 类中实现 collectionView..
    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    相关资源
    最近更新 更多