我处理以下问题:在主VC上我有一个TableView,在容器视图控制器上我有一个textField。我想添加每个文本,我在容器中输入自动显示为主VC中tableView的新行
到目前为止,我使用segue将数据从主VC发送到容器。但是我应该以相反的顺序执行相同的操作呢?我虽然在容器视图中实现了主VC的委托,但我不知道如何正确地做到这一点。或者可能存在更常见的解决方案。
无论如何,这是我的代码:
class MessageViewController: UIViewController {
var currentUser: User!
var containerViewController: InputTextViewController?
@IBOutlet weak var enterMessageView: UIView!
@IBOutlet weak var messageTableView: UITableView!
}
extension MessageViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "moveToInputText" {
let connectContainerViewController = segue.destination as? InputTextViewController
containerViewController = connectContainerViewController
containerViewController?.userSendMessageTo = currentUser
}
}
}
extension MessageViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentUser.mesaageHistory.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as! ChatMessageTableViewCell
let data = currentUser.mesaageHistory[indexPath.row]
cell.messageLabel.text = data.messageText
return cell
}
}
class InputTextViewController: UIViewController {
@IBOutlet weak var messageTextField: UITextField!
var userSendMessageTo: User!
weak var delegate = MessageViewController()
@IBAction func sendMessge(_ sender: Any) {
handleSend()
userSendMessageTo.mesaageHistory.append(message)
print(userSendMessageTo.mesaageHistory[0].messageText)
let row = userSendMessageTo.mesaageHistory.count - 1
let insertIndexPath = IndexPath(item: row, section: 0)
print(userSendMessageTo.mesaageHistory.count)
delegate?.messageTableView.beginUpdates()
delegate?.messageTableView.insertRows(at: [insertIndexPath], with: UITableViewRowAnimation.automatic)
delegate?.messageTableView.endUpdates()
}
}
答案 0 :(得分:0)
以下是如何使用'委托'模式正确
协议声明&代表成员
protocol InputTextViewControllerDelegate: class {
func someFunc()
func anotherFunc()
}
class InputTextViewController: UIViewController {
weak var delegate: InputTextViewControllerDelegate?
}
协议实施&设置委托属性
extension MessageViewController, InputTextViewControllerDelegate {
// MARK: InputTextViewControllerDelegate
//
func someFunc()
{
}
func anotherFunc()
{
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "moveToInputText" {
let connectContainerViewController = segue.destination as? InputTextViewController
containerViewController = connectContainerViewController
containerViewController
}
}
}