gpt4 book ai didi

ios - 如何将数据从 UI Table View 传递到 Table View Cell 内的 UI Collection View?

转载 作者:行者123 更新时间:2023-11-29 05:57:32 26 4
gpt4 key购买 nike

我使用 xib 在我的 TableView 单元格上有 ui Collection View 。我想将从 API 获取的数据传递到 TableView 单元格内的 ui Collection View

这是我的代码

型号

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 = ""


}

表格 View

 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)
}
}

}

TableView 单元格内的 Collection View

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)

}


}

最佳答案

    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

关于ios - 如何将数据从 UI Table View 传递到 Table View Cell 内的 UI Collection View?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54995542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com