我使用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)
}
}
答案 0 :(得分:0)
您必须以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
,在columns
中添加MessageTextType
变量数组
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
答案 1 :(得分:0)
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