簡體   English   中英

如何將數據從UI Table View傳遞到Table View Cell中的UI Collection View?

[英]How to pass data from UI Table View to UI Collection View inside Table View Cell?

我使用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)

}


}

您必須在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
    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

暫無
暫無

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

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