【发布时间】:2018-03-19 20:59:00
【问题描述】:
我正在尝试在我的应用程序中实现聊天大厅。我有一个UITableViewCell,它以编程方式添加了一个标签。但是在启动时,什么都没有显示。这是我的ViewController 代码,其中包含UITableView:
import UIKit
import Firebase
class MessagesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
private var ContactNames = [String]()
private var ContactPicturesURLs = [String]()
@IBOutlet weak var ChatsTableView: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
ChatsTableView.dataSource = self
ChatsTableView.delegate = self
self.view.layer.backgroundColor = UIColor.white.cgColor
populateActiveChats()
}
private func populateActiveChats()
{
let loggedOnUserID = Auth.auth().currentUser?.uid
let ref = Constants.refs.databaseChatsLite.child(loggedOnUserID!)
// Retrieve the products and listen for changes
ref.observe(.value, with:
{ (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot]
{
// Code to execute when new product is added
let chatValueDictionary = child.value as? NSDictionary
self.AddChatToCollections(chatAsDictionary: chatValueDictionary)
self.DispatchQueueFunc()
}
})
}
func AddChatToCollections(chatAsDictionary: NSDictionary!)
{
let contactName = chatAsDictionary["userName"] as! String
self.ContactNames.append(contactName)
}
func DispatchQueueFunc()
{
DispatchQueue.main.async
{
self.ChatsTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return ContactNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = ChatsTableView.dequeueReusableCell(withIdentifier: "chat_room_cell", for: indexPath) as! PrivateChatUITableViewCell
var index = indexPath.row
cell.ContactName.text = ContactNames[index]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
chatIndexToLoad = indexPath.row
performSegue(withIdentifier: "segue_to_chatroom", sender: self)
}
var chatIndexToLoad: Int = -1
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if (segue.identifier == "segue_to_chatroom")
{
let destination = segue.destination as! PrivateChatViewController
destination.senderId = Constants.refs.currentUserInformation?.uid
destination.senderDisplayName = Constants.refs.currentUserInformation?.displayName
}
}
}
这是我TableViewCell的代码:
import UIKit
class PrivateChatUITableViewCell: UITableViewCell
{
var ContactName: UILabel!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
commonInit()
}
func commonInit()
{
ContactName = UILabel()
self.addSubview(ContactName)
}
override func layoutSubviews()
{
let margins = self.contentView.layoutMarginsGuide
ContactName.center = self.center
}
}
但我的单元格显示为空白,如果它确实显示的话:
我确实调试了我的代码并确保单元格获取文本以显示在其标签中,因此它不是空的,如下图所示:
有没有人解决标签不出现的问题?
另外,我在PrivateChatUITableViewCell 中调试了commonInit 函数,它确实命中了addSubView 和约束命令
【问题讨论】:
标签: ios swift uitableview tableview